フィルターのクリア

For loops - Textbook Example

1 回表示 (過去 30 日間)
Maroulator
Maroulator 2014 年 8 月 3 日
編集済み: Image Analyst 2014 年 8 月 3 日
I have the following code from a textbook exercise which asks me to arrive at the value of ires; the answer key has ires=25 as the answer. After struggling with the exercise, I think I have the logic down, but I need this additional clarification. It is my understanding that after MATLAB encounters the break statement, it stops the inner loop and goes to the next statement after the end of the inner loop; in this case, the "next statement" is ires=ires+1. My question is this: am I correct in assuming that once index2==6, ires=ires+1 doesn't run (ie. ires doesn't get incremented)?
ires=0;
for index1=1:10
for index2=index1:10
if index2==6
break;
end
ires=ires+1;
end
end

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 3 日
When the condition is met, Matlab will exist the loop, which means ires will not be incremented. All instructions after break, inside the for loop will be skiped

その他の回答 (1 件)

Image Analyst
Image Analyst 2014 年 8 月 3 日
Not correct. The "if" is not a loop so it doesn't start up with the ires line right after the if block. It breaks out of the index2 loop and continues on with the index1 loop (which may enter the index2 loop again if index1 is not 10).
  3 件のコメント
Maroulator
Maroulator 2014 年 8 月 3 日
Thanks. Could you please also comment on the following? I can see how in the first iteration of the outer loop, index1=1 and index2 goes from 1 to 10. Am I correct in assuming that in the second iteration of the for loop, index1=2 and index2 goes from 2 to 10?
Image Analyst
Image Analyst 2014 年 8 月 3 日
編集済み: Image Analyst 2014 年 8 月 3 日
Correct. Though index2 will never make it all the way to 10 because it will bail out once it gets to 6. So on the first loop ires will be 1,2,3,4,5, then on the next loop it will be incremented 4 times (for index2 = 2 through 5) and ires will be 6,7,8,9. Then the third outer iteration starts and so on.

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

カテゴリ

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