Can I change the loop size inside the loop?

7 ビュー (過去 30 日間)
sakib shalehin
sakib shalehin 2018 年 4 月 16 日
編集済み: Stephen23 2018 年 4 月 16 日
for i=1:s
statements
end
here,can i change the value of s inside the loop.
  1 件のコメント
Birdman
Birdman 2018 年 4 月 16 日
Where is your entire code?

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

回答 (1 件)

David Fletcher
David Fletcher 2018 年 4 月 16 日
編集済み: David Fletcher 2018 年 4 月 16 日

For loop conditions are set upon entering the loop and the only form of modification that can be made is to 'break' out of the loop early. If you need a indeterminate loop duration use a while loop where the loop condition is checked upon every iteration. From the for loop docs:

Avoid assigning a value to the index variable within the loop statements. The for statement overrides any changes made to index within the loop

Although this only explicitly mentions the loop index variable, it also extends to the end counter:

s=5;
for iter=1:s
    iter
    s=3;
end

>> test

iter =

     1

iter =

     2

iter =

     3

iter =

     4

iter =

     5

As can be see, the attempt to assign 3 to the loop end condition has been ignored

カテゴリ

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