How to modify Loop variable inside the loop body

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?

 Respuesta aceptada

Jan
Jan el 30 de Jun. de 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 comentarios

Vatsal Gupta
Vatsal Gupta el 1 de Jul. de 2018
Thanks. I changed for into while and it worked :)
Thank you once again, Jan!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2017a

Etiquetas

Preguntada:

el 30 de Jun. de 2018

Comentada:

el 16 de En. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by