MATLAB: Probability of a run of k heads or more in N tosses of a fair coin N>>k

Image Processing Toolboxprobability

is there a code for this. One solution is given in http://www.drdobbs.com/architecture-and-design/20-heads-in-a-row-what-are-the-odds/229300217 Good discussion… gives answer

Best Answer

It's pretty trivial if you have the Image Processing Toolbox:
numberOfTosses = 1000000;
% Throw coin numberOfTosses times with tails defined as 0, heads as 1.
tosses = randi(2, 1, numberOfTosses)-1;
% Use the Image Processing Toolbox to find stretches of N.
N = 20; % Look for 20 in a row.
measurements = regionprops(logical(tosses), 'area');
% Extract the lengths of all stretches of heads in a row.
allRuns = [measurements.Area];
% Count the number of times it's N or more
numberOfLongStretches = sum(allRuns >= N)
Related Question