如何在 MATLAB 中绘制这些抛硬币结果?
我正在编写一个脚本来表示一枚硬币翻转 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需在这里循环。只是
No need to loop here. Just
首先,您将所需的数据存储在向量
B
和C
中,因此没有真正的理由在内调用绘图命令你的循环。循环完成后只需绘制一张图即可。其次,当您调用 PLOT 时,您正在传递循环变量< code>k 作为第一个参数,并且在循环结束时它只有一个值 100。这就是为什么
fraction
中的所有点都以 x 值 100 绘制。要获得所需的图,只需在循环之后执行此操作:
或者,您不不必存储向量
B
。你可以在循环之后执行此操作:Firstly, you're storing the data you need in your vectors
B
andC
, 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 infraction
are plotted at an x value of 100.To get the plot you want, just do this after your loop:
Alternatively, you don't have to store the vector
B
. You could just do this after your loop: