How to break a for loop but run it one more time?

8 visualizzazioni (ultimi 30 giorni)
James Tate
James Tate il 28 Nov 2017
Modificato: Jan il 28 Nov 2017
I have a for loop that runs from i=1:n, but once an equation is satisfied in an if statement I want the for loop to end AND then run 1 more time, for example if it stops on 4 I want it to still run 5, then stop. Is there any way to do this?

Risposte (2)

Jan
Jan il 28 Nov 2017
Modificato: Jan il 28 Nov 2017
n = 20;
stop = false;
for k = 1:n
... your calculations are here
fprintf('Execute %d\n', k);
if stop
fprintf('Leave the loop\n');
break;
end
if k == 7 % Insert your condition here
fprintf('Matching condition\n');
stop = true;
end
end

Walter Roberson
Walter Roberson il 28 Nov 2017
equation_is_satisfied = false;
for i = 1 : n
...
if equation_is_satisfied %it was satisfied on _previous_ loop iteration
break;
end
if some condition establishing that equation is satisfied on _this_ loop iteration
equation_is_satisfied = true;
end
end

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by