如何在 MATLAB 中绘制这些抛硬币结果?

发布于 2024-11-07 23:14:56 字数 398 浏览 2 评论 0原文

我正在编写一个脚本来表示一枚硬币翻转 100 次,并且我想绘制随着这 100 次试验的进行,“正面”出现的百分比。我似乎无法绘制显示头/试验数量与试验 1 到 100 的图。该图显示 x 轴上 100 点处的所有头/试验。

这是我正在使用的代码:

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

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 the 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仙女 2024-11-14 23:14:56

无需在这里循环。只是

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

No need to loop here. Just

> n= 100;
> trials= 1: n;
> x= rand(1, n);
> C= cumsum(x< .5);
> plot(trials, C./ trials)
琉璃梦幻 2024-11-14 23:14:56

首先,您将所需的数据存储在向量 BC 中,因此没有真正的理由在调用绘图命令你的循环。循环完成后只需绘制一张图即可。

其次,当您调用 PLOT 时,您正在传递循环变量< code>k 作为第一个参数,并且在循环结束时它只有一个值 100。这就是为什么 fraction 中的所有点都以 x 值 100 绘制。

要获得所需的图,只需在循环之后执行此操作:

plot(B,C./B);

或者,您不不必存储向量B。你可以在循环之后执行此操作:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文