While loop with random walk

2 次查看(过去 30 天)
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

回答(1 个)

Shunichi Kusano
Shunichi Kusano 2019-8-13
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.

类别

Help CenterFile Exchange 中查找有关 Particle & Nuclear Physics 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by