I need to get out of a nested loop when a particular condition is satisfied. I tried to insert the "break", "return" and "continue" commands but it does not seem to make the necessary effect.
10 ビュー (過去 30 日間)
古いコメントを表示
for i = 1 : n % iterating over all the 'n' particles
for z=1:2000
if (p(i,2)<A && wave(z,2)==20)
sticking_coeff=0.7
rdm_nbr1=rand(1)
if rdm_nbr1>sticking_coeff
v(i,2)=-v(i,2);
v(i,1)=-v(i,1);
else
v(i,1)=0;
v(i,2)=0;
end
elseif (p(i,2)<A && wave(z,2)==0)
p(i,1)
v(i,1)=v(i,1);
v(i,2)=v(i,2);
if (p(i,1)<wave(z,1))
sticking_coeff=0.7 ;
rdm_nbr=rand(1);
if rdm_nbr>sticking_coeff
v(i,2)=-v(i,2);
v(i,1)=-v(i,1);
else
v(i,1)=0;
v(i,2)=0;
end
end
else
v(i,2)=v(i,2);
v(i,1)=v(i,1);
end
end
end
Now, what I would want to happen, is that whenever the condition for i='n' is satisfied, then the inner loops should stop and the control should come back to the first 'for' loop, but is currently happening is that the second 'for' loop is executing for 2000 times before it comes out of the loop. Kindly help.
0 件のコメント
採用された回答
Image Analyst
2013 年 12 月 22 日
Why not just have your outer for loop go from 1 to (n-1) then, instead of to n? If you went all the way to n, you can't start that loop all over again with i = 1 - you'd have to use a while loop for that kind of logic but then you'd need some logic to prevent it from being an infinite loop. When would it ever stop if it just keeps restarting whenever i hit n?
2 件のコメント
Image Analyst
2013 年 12 月 23 日
Use break to leave the z loop and continue with the i loop. Use continue to skip the rest of the z loop and start with the next z value.
if (some condition)
break; % out of z loop and continue with the i loop.
end
If you need to break out of two loops , then you will need to set a flag or else check if the inner loop is not greater than or equal to the last value. For example, after the z loop
if z < 1000
break; % break out of "i" loop also.
end
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!