While loop with random walk

16 ビュー (過去 30 日間)
Not_sharpest_tool.mat
Not_sharpest_tool.mat 2019 年 8 月 13 日
回答済み: Shunichi Kusano 2019 年 8 月 13 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by