Code covered by the BSD License  

Highlights from
Coin And Dice

from Coin And Dice by Rodolphe Sitter
Simulate the average number of tosses of coin/throws of dice to get a given sequence.

CoinToss(Seq,N)
function CoinToss(Seq,N)
%COINTOSS 
%   Compute the estimated average number of coin tosses to get a given
%   sequence.
%
%   CoinToss(Seq,N)
%
%==========================================================================
%   INPUTS:
%
%   Seq   	- Sequence (row vector) of integers ranging from 0 to 1 
%            (corresponding to either Tails or Heads).
%
%   N       - Number of Monte-Carlo Simulations
%
%==========================================================================
%   EXAMPLE:
% >>   CoinToss([1,1,0,1],10^4))
%
% >>   OUTPUT:
%      THE SEQUENCE IS: 
%            1     1     0     1
%      The average number of tosses to get this sequence is:  18  
%      (Sample Mean= 18.27 standard deviation=  0.15))
%
%**************************************************************************
% Rodolphe Sitter - MSFM Student - The University of Chicago
% March 27, 2009
%**************************************************************************

M=length(Seq);
C=rand(M,N)>.5;
Count=zeros(N,1);

for j=1:N  
    c=M;
    while min(C(:,j)==Seq')==0
        C(1:M-1,j)=C(2:M,j);
        C(M,j)=rand(1,1)>.5;
        c=c+1;
    end
    Count(j)=c;    
end

Mean=mean(Count);
STD_err=std(Count)/sqrt(N);
fprintf('\n==============================================================')
fprintf('\n          COIN TOSSING BY MONTE-CARLO SIMULATION          \n\n')
disp('THE SEQUENCE IS: ')
disp(Seq)
fprintf('The average number of tosses to get this sequence is:%4.0f  \n',round(Mean));
fprintf('(Sample Mean=%6.2f standard deviation=%6.2f)\n\n',Mean,STD_err);

Contact us at files@mathworks.com