开发者

How can I plot these coin toss results in MATLAB?

开发者 https://www.devze.com 2023-03-06 11:49 出处:网络
I\'m writing a script to represent a coin flipped 100 times and I want to plot the percentage of occurrences for \"heads\" as these 100 trials progress. I can\'t seem to get the plot to display the nu

I'm writing a script to represent a coin flipped 100 times and I want to plot the percentage of occurrences for "heads" as these 100 trials progress. I can't seem to get the plot to display the number of heads/trials versus trials 1 through 100. The plot shows all of the heads/trials at th开发者_JAVA技巧e 100 point on the x-axis.

This is the code I am using:

counter=0
wins=0
for k=1:100
    x=rand
    counter=counter+1
    if (x<0.5)
        x_coin=0
    else
        x_coin=1
        wins=wins+1    
    end
    B(k)=counter
    C(k)=wins
    fraction=C.*(1./B)
    plot(k,fraction)
end


No need to loop here. Just

> n= 100;
> trials= 1: n;
> x= rand(1, n);
> C= cumsum(x< .5);
> plot(trials, C./ trials)


Firstly, you're storing the data you need in your vectors B and C, so there's no real reason to also call your plot command within your loop. Just make one plot after your loop is done.

Secondly, when you call PLOT, you're passing your loop variable k as the first argument, and it only has a single value of 100 at the end of your loop. This is why all of your points in fraction are plotted at an x value of 100.

To get the plot you want, just do this after your loop:

plot(B,C./B);

Alternatively, you don't have to store the vector B. You could just do this after your loop:

B = 1:100;
plot(B,C./B);
0

精彩评论

暂无评论...
验证码 换一张
取 消