Help with coin toss loop

28 views (last 30 days)
Kathryn Janiuk
Kathryn Janiuk on 7 Nov 2020
Commented: Kathryn Janiuk on 8 Nov 2020
Hi, so I am very new at this! I am writing a code that is trying to simulate a fair coin toss that flips a coin 100x with -1 being tails and 1 being heads. I am then trying to run this 100 times and find the mean of those 100 samples and put it into a histogram.
Here is what I have written currently:
samplesize = 50;
nsamples=100;
coins = (binornd(1,.5,nsamples,1)*2)-1;
count_toss = mean(coins);
for i = 1:100
mean(count_toss)
end
lots_toss = mean(count_toss);
Bins = 10;
histfit(lots_toss,10);
When I run this I get:
Error using histfit (line 94)
Not enough data in X to fit this distribution.
Error in coin_toss (line 15)
histfit(lots_toss,10);
I also generate the same mean for the loop, when I am trying to generate 100 different means for the histogram.
I'm not sure what I'm missing but I think I need to change something in the loop index, but I'm not entirely sure of how to code it and have been searching how to do this-I think right now I have it hard programmed in to just display the same number repeatedly which is why I'm getting the error I'm seeing down below. If someone can help point me in the right direction on how to alter this slightly I think it should be okay? I'm fairly sure it's not THAT far off.
Thank you!!

Accepted Answer

John D'Errico
John D'Errico on 8 Nov 2020
There is no need to use a loop.
First, get used to using meaningful variable names. You have samplesize, and nsamples. What do they mean? I'll guess this:
nsim = 10000; % how many simulated runs? Here I used 10000 total simulated runs.
tossespersim = 100; % each simulated run has 100 coin tosses
There is no need to use binornd at all. But you can if you want to do so. Rand is simpler.
p = 0.5; % the coin is fair. p is the probability of a head
coins = (rand(nsim,tossespersim) <= p)*2 - 1; % -1 means we got a tail, 1 is a head.
Now just use mean to compute the means.
meantoss = mean(coins,2);
meantoss will be a vector of of length nsim.
size(meantoss)
ans = 1×2
10000 1
The histogram is simple.
nbins = 10;
histfit(meantoss,nbins)
  1 Comment
Kathryn Janiuk
Kathryn Janiuk on 8 Nov 2020
Oh my gosh, thank you for being so thorough! I learned a lot from this, I really appreciate it!

Sign in to comment.

More Answers (1)

David Hill
David Hill on 8 Nov 2020
Edited: David Hill on 8 Nov 2020
a=mean((-1).^randi(2,100));
histogram(a,100);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!