for loop and break!!!

5 ビュー (過去 30 日間)
ck
ck 2016 年 5 月 3 日
コメント済み: ck 2016 年 5 月 3 日
for(syntax)-(1st for loop)
for(syntax)(2nd for loop)
if(...)
value
break
end
else(..)
value
end
...
....
...
so would the break help in coming out from the first and second for loop , or just second for loop??

採用された回答

Image Analyst
Image Analyst 2016 年 5 月 3 日
You need to set a flag to break out of the outer loop
finishNow = false;
for k1 = 1 : 1000
for k2 = 1 : 3000
if someCondition
finishNow = true;
break; % out of inner loop.
end
end
if finishNow
break; % out of outer loop.
end
end
  1 件のコメント
ck
ck 2016 年 5 月 3 日
Thanks guys!

サインインしてコメントする。

その他の回答 (1 件)

CS Researcher
CS Researcher 2016 年 5 月 3 日
Break will work for the loop it is in, so the second for loop. It is always good to run an example and check:
for i = 1:10
for j = 1:2
if j == 2
break;
else
fprintf('(i,j) = (%d,%d)\n',i,j);
end
end
end
As you will see i goes all the way from 1 to 10 but j is always 1. 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