Is it possible to change the upper end for the runtime variable of for loop during it's runtime?

14 ビュー (過去 30 日間)
The problem I have, is that I have a for-loop that iterates up to a certain number, but that number can increase during the runtime of the for-loop. As an example:
max = 10;
for i = 1:2:max
max = max + 1;
end
Is the value of i 10? Or is it more, i.e. does i run until it has caught up to max?
Thank you!

採用された回答

dpb
dpb 2014 年 1 月 14 日
編集済み: dpb 2014 年 1 月 14 日
No, the limit is stored and not updated even if the limit variable is modified...this is easily enough tested (and it's in the doc's somewhere altho not in the text help for for).
>> N=4;for i=1:N, disp(i), if i==3, N=N+1; end,end
1
2
3
4
>> disp(N)
5
>>
Use a while loop or similar construct instead of for to have a dynamic upper limit ( break may be your friend here, too).

その他の回答 (1 件)

Dana Adkins
Dana Adkins 2014 年 1 月 14 日
In short, “No.”
By just quickly running your example script the workspace variables end up being i=9 and max = 15 which would imply that while you can modify max however a copy of max’s value is used for the loop limit and not your newly modified max value.
This is not a practice I would recommend in any case.
  1 件のコメント
Daniel
Daniel 2014 年 1 月 14 日
If I could work around that, I would. Unfortunately, I see no alternative.
Thanks anyway.

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

カテゴリ

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