How to modify Loop variable inside the loop body

13 Ansichten (letzte 30 Tage)
Vatsal Gupta
Vatsal Gupta am 30 Jun. 2018
Kommentiert: Douglas Anderson am 16 Jan. 2019
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?

Akzeptierte Antwort

Jan
Jan am 30 Jun. 2018
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 Kommentare
Vatsal Gupta
Vatsal Gupta am 1 Jul. 2018
Thanks. I changed for into while and it worked :)
Douglas Anderson
Douglas Anderson am 16 Jan. 2019
Thank you once again, Jan!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by