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
Firstly, you’re storing the data you need in your vectors
BandC, 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
kas 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 infractionare 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: