repeat a condition from the first iteration of for loop

4 visualizaciones (últimos 30 días)
hamed
hamed el 27 de Jul. de 2014
Comentada: hamed el 27 de Jul. de 2014
I have an 'if' condition in a 'for' loop. But, the problem is when the condition is true and the code do sth then it continue the loop from the point that condition becomes true. Instead, I want that the code repeat the loop from the first iteration.

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 27 de Jul. de 2014
Hamed - if your for loop is something like
for k=1:n
then you can replace it with a while loop and allow the looping to continue from the first iteration whenever your condition is true
k = 1;
while k<=n
if condition is true
% do something
% reset k to repeat loop from first iteration
k = 1;
else
k = k + 1;
end
end
The only trick is making sure that you don't get stuck in this loop. When would the condition be false for all iterations that would finally cause the code to exit the loop?
  5 comentarios
Geoff Hayes
Geoff Hayes el 27 de Jul. de 2014
Does this not work?
for i=2:m
% do sth
k=i-1;
while k>=1
% do sth
if condition is true
% do sth
k = i - 1; % to start the loop again
else
k = k - 1; % to decrement
end
end
end
Or am I misunderstanding your question? You stated that you want that the code repeat the loop from the first iteration and I want the interior for loop (k) will be repeated from the first if condition becomes true.
hamed
hamed el 27 de Jul. de 2014
Ok, thank you very much. I guess this should work. I will test it tomorrow when back to uni cause i don't have matlab at home.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by