Explain how many times a for loop will execute

2 ビュー (過去 30 日間)
Jorge Rodriguez
Jorge Rodriguez 2020 年 10 月 10 日
コメント済み: Jorge Rodriguez 2020 年 10 月 10 日
I can add ires to see the result, I am not sure how to see how many times the loops will execute. If someone could explain how to do this that would be helpful. I have done several searches and tried using the break function, but if its really big number says -32687:32688, how does one tell how many times it loops. without counting each 64560 times. I have figured it out on smaller loops by putting the ii at the bottom of the code. This has a loop within a loop and I am lost.
ires = 0;
for index1 = 10: -2: 1
for index2 = 2:2:index1
if index2 == 6
break;
end
ires = ires + index2;
end
end

回答 (1 件)

Mario Malic
Mario Malic 2020 年 10 月 10 日
ires = 0;
for index1 = 10: -2: 1
for index2 = 2:2:index1
if index2 == 6
break;
end
ires = ires + 1; % index2 for what?
end
end
MATLAB enters first loop with index1 = 10, then proceeds in the second loop with index2 = 2. Within second loop it checks the if condition and adds 1 to ires. When the 'if' condition is fulfilled, it exits the second loop, and returns in the first one with index1 = 8 and so on.
  8 件のコメント
Mario Malic
Mario Malic 2020 年 10 月 10 日
編集済み: Mario Malic 2020 年 10 月 10 日
Your code is working, n_times counts both loops.
Jorge Rodriguez
Jorge Rodriguez 2020 年 10 月 10 日
Okay, I just thought it was counting loop one. Well i gave it a solid try. Thanks for your help.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by