How to modify Loop variable inside the loop body

13 ビュー (過去 30 日間)
Vatsal Gupta
Vatsal Gupta 2018 年 6 月 30 日
コメント済み: Douglas Anderson 2019 年 1 月 16 日
for i=1:10
if randi(10)==3
i=i-1;
end
end
In the above code, i must get reduced by 1 whenever the if condition comes true. But it doesn't gets so. Any modifications so that loop variable i gets modified inside the loop body?

採用された回答

Jan
Jan 2018 年 6 月 30 日
This does not work in a for loop, but in while:
i = 1;
while i <= 10
disp(i)
...
i = i + 1;
if randi(10) == 3
i = i-1; % Or i - 2?
end
end
  2 件のコメント
Vatsal Gupta
Vatsal Gupta 2018 年 7 月 1 日
Thanks. I changed for into while and it worked :)
Douglas Anderson
Douglas Anderson 2019 年 1 月 16 日
Thank you once again, Jan!

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by