Search code examples
matlabfor-loopcoin-flipping

flip coin 100 times get exactly 50 Matlab


If I flip a coin 100 times, what is the probability that exactly 50 will be heads? My thoughts were to get the number of times exactly 50 appeared in the 100 coin flips out of 1000 times and divide that by 1000, the number of events. I have to model this experiment in Matlab. I understand that flipping a coin 100 times and retrieving the number of heads and adding a count to the number of exactly 50 heads is one event. But I do not know how to repeat that event 1000, or 10000 times.

Here is the code I have written so far:

total_flips=100;
heads=0;
tails=0;
n=0;
for z=1:1000
%tosses 100 coins 
for r=1:100
    %randomizes to choose 1 or 0, 0 being heads
    coin=floor(2*rand(1));
    if (coin==0)
        heads=heads+1;
    else
        tails=tails+1;
    end
end

if heads==50
    n=n+1;
end
end

I have tried to encompass the for loop and the if statement within a for loop, but had no luck. How do I repeat it?


Solution

  • You don't need tails at all, and you need to set heads back to zero inside the outer for z=1:1000 loop.