MATLAB: Repeat a condition from the first iteration of for loop

forrepeat

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.

Best Answer

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?
Related Question