Help with coin toss loop
Ältere Kommentare anzeigen
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!!
1 Kommentar
Jasson
am 30 Apr. 2025
You're actually really close — great start, especially if you're just getting into this!
The main issue is that you're calculating the mean of the same coin toss 100 times in the loop, instead of generating 100 different toss samples and storing their means. That’s why you’re getting the same number over and over, and why histfit is complaining — it only sees one value instead of a whole list.
Here’s how you can fix it in a simple way:
samplesize = 50; % Number of coin tosses per sample
nsamples = 100; % Number of samples
means = zeros(nsamples,1); % Store the mean of each sample
for i = 1:nsamples
coins = (binornd(1, 0.5, samplesize, 1) * 2) - 1; % Simulate coin tosses: -1 = tails, 1 = heads
means(i) = mean(coins); % Store the mean of this sample
end
% Now plot the histogram of the means
histfit(means, 10); % 10 bins for the histogram
This version generates 100 different samples, calculates the mean for each, and then plots all the means in a histogram with a fitted curve. Now you'll get a proper distribution!
Let me know if you want to try other visualizations too!
Akzeptierte Antwort
Weitere Antworten (1)
David Hill
am 8 Nov. 2020
Bearbeitet: David Hill
am 8 Nov. 2020
a=mean((-1).^randi(2,100));
histogram(a,100);
1 Kommentar
senthil
am 23 Okt. 2025
Kategorien
Mehr zu Noncentral t Distribution finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
