Problem with break statement
4 ビュー (過去 30 日間)
古いコメントを表示
I have a code:
for i=1:n
for j=1:n
if 'some condition'
'some logic'
if 'some condition'
break
end
end
end
end
now my question is that if the 2nd if statement is true and it breaks shouldnt it end the 2nd for loop since if statement is under 2nd for loop but whenever I run this if the 2nd if statement is true and it breaks it ends the 1st for loop.
Any guidance is highly appreciated.
0 件のコメント
採用された回答
Adam Danz
2020 年 11 月 17 日
編集済み: Adam Danz
2020 年 11 月 17 日
> ...shouldn't it end the 2nd for loop since if statement is under 2nd for loop... ?
Yes, it should end the 2nd loop and that's what it's doing. To better understand what's going on, I inserted fprintf commands in each loop so you can see the iteration numbers. The first condition is true when j==2 and the second nested condition is true when i==3 (while j is equal to 2).
clc
n = 4;
for i=1:n
j = NaN;
fprintf('\n i=%d, j=%d',i,j)
for j=1:n
fprintf('\n i=%d, j=%d',i,j)
if j==2
fprintf(' CONDITION 1')
if i==3
fprintf(' & CONDITION 2: breaking')
break
end % end i==2 test
end % end j==2 test
end
end
fprintf('\n')
You can see (below) that the break condition occurs when i==3 and j==2 and on the next iteration, the i-loop interates to i==4 and the j-loop resets.
6 件のコメント
その他の回答 (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!