Vector y seems to change without my modifying it

In this short script I'm trying to simulate three coin flips in a row. The code and output are below.
Notice that in this particular run of the script, vector y comes out to be [1 1 1]. I display each element after each iteration, but after the for loop is completed, when I display vector y, it comes out as [0 0 1].
I've run this script numerous times and the final display statement always comes out different from what is indicated in the element-by-element display.
Have no idea why this is happening.
Thanks, Patrick
%*****************
clear disp('start')
M=3
for i= 1:M
disp(i)
a=rand(1,1)
if a<0.1
y(1,M)=0;
else
y(1,M)=1;
end
disp(y(1,M));
end;
disp(y)
%**************
OUTPUT OF ABOVE SCRIPT
start
M =
3
1
a =
0.7635
1
2
a =
0.6279
1
3
a =
0.7720
1
0 0 1

 Respuesta aceptada

Star Strider
Star Strider el 26 de Ag. de 2014
The problem is in your y assignments:
y(1,M)=0;
and:
y(1,M)=1;
Change the reference to:
y(1,i)=0;
and:
y(1,i)=1;
to see if that produces the result you want.

Más respuestas (1)

Sean de Wolski
Sean de Wolski el 26 de Ag. de 2014

0 votos

Use the debugger!
Put a break point on the first line of the loop. Run the file and then step through. This will help you see where y changes (or displays) and more importantly help you learn to debug.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 26 de Ag. de 2014

Respondida:

el 26 de Ag. de 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by