While loop with random walk

2 visualizaciones (últimos 30 días)
Not_sharpest_tool.mat
Not_sharpest_tool.mat el 13 de Ag. de 2019
Respondida: Shunichi Kusano el 13 de Ag. de 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

Respuestas (1)

Shunichi Kusano
Shunichi Kusano el 13 de Ag. de 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.

Categorías

Más información sobre Particle & Nuclear Physics en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by