- #1
Poisonous
- 26
- 0
EDIT:: I figured out the problem with the loop was that I needed an 'and' statement, not an 'or' statement.. BUT I'm still having the problem where my random number is always the same.
I can't figure out why this is loop is infinite (I think it's the while loop). I'm new to Matlab specifically, so it might be something in the syntax.
The point of this program is to start in the middle of the array (at point M(3,3)), then move around the matrix until it hits one of the boundary -1's or 1's. Then the while loop stops and adds either the 1 or -1 to the expecVal variable. Based off the matrix, the variable expecVal should be about 0 at the end. I know there are more efficient ways of writing this program, but the point was just to write a quick simulation, and this is the first way I thought to do it.
I can't figure out why this is loop is infinite (I think it's the while loop). I'm new to Matlab specifically, so it might be something in the syntax.
The point of this program is to start in the middle of the array (at point M(3,3)), then move around the matrix until it hits one of the boundary -1's or 1's. Then the while loop stops and adds either the 1 or -1 to the expecVal variable. Based off the matrix, the variable expecVal should be about 0 at the end. I know there are more efficient ways of writing this program, but the point was just to write a quick simulation, and this is the first way I thought to do it.
Code:
M = zeros(5);
M(1,3) = -1;
M(2,2) = -1;
M(2,4) = 1;
M(3,1) = 1;
M(3,5) = 1;
M(4,1) = -1;
M(4,5) = -1;
M(5,2) = 1;
M(5,3) = -1;
M(5,4) = 1;
rand = rand();
expecVal = 0;
z = 3;
x = 3;
for i=1:10
while M(z,x) ~= 1 || M(z,x) ~= -1
rand = rand();
if rand < .25
z=z+1;
elseif .25 < rand < .5
z=z-1;
elseif .5 < rand < .75
x=x+1;
else
x=x-1;
end
end
expecVal = expecVal + M(z,x);
z = 3;
x = 3;
end
expecVal
Last edited: