MATLAB Answers

0

While loop with random walk

Asked by Not_sharpest_tool.mat on 13 Aug 2019
Latest activity Answered by Shunichi Kusano on 13 Aug 2019
I'm doing a random walk problem and i need to make it so that when the walker goes over a certain position it gets reflected back onto the center (position=0). For this I'm trying to use while loops but they seem to get stuck. The program works fine until it reaches one of its limits (-10 or 10) then the while loops are supposed to prevent the position from going further and instead send the position closer to the center. The while loops seem to do this only once, then the program gets stuck and has to be forcefully ended. I suspect that there is a problem with how the while loops are written. How do I correct this problem?
num_stp=2000;
position=zeros(size(num_stp));
for i=1:num_stp
walk(i)=randi(2);
if walk(i)==1
position(i+1)= position(i)-1;
elseif walk(i)==2
position(i+1)= position(i)+1;
while position(i)<=-10
if walk(i)==1
position(i+1)=position(i)+1;
elseif walk(i)==2
position(i+1)=position(i)+1;
end
end
while position(i)>=10
if walk(i)==1
position(i+1)=position(i)-1;
elseif walk(i)==2
position(i+1)=position(i)-1;
end
end
end

  0 Comments

Sign in to comment.

1 Answer

Answer by Shunichi Kusano on 13 Aug 2019

I'm not sure if this is exactly what you want.
clear
num_stp=2000;
position=zeros(size(num_stp));
for i=1:num_stp
walk(i)=randi(2);
if walk(i)==1
position(i+1)= position(i)-1;
elseif walk(i)==2
position(i+1)= position(i)+1;
end
if abs(position(i+1)) > 10
position(i+1) = position(i+1) - sign(position(i+1))*2;
end
end
hope this helps.

  0 Comments

Sign in to comment.