Vector y seems to change without my modifying it
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Star Strider
on 26 Aug 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.
0 Comments
More Answers (1)
Sean de Wolski
on 26 Aug 2014
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.
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!