Azzera filtri
Azzera filtri

Trouble with For loop within If statement.

1 visualizzazione (ultimi 30 giorni)
Mark
Mark il 8 Nov 2011
I'm trying to solve a problem for multiple iterations until the error (err) for some the interior points (ii=2:imax-1) (imax is the length of the vector) in the t vector is below a certain value (errmax).
llmax is an arbitrary large number to allow as many iterations as necessary. I want first for loop to stop when the error at the interior points in the t vector are at or below errmax. I'm trying to accomplish this using an if and break within the first for loop. Within the if statement is another for loop checking the error of the interior points. I'm having trouble getting this to work. The break statement does not seem to associate with the original for loop. Or perhaps something else is wrong.
for ll=1:llmax
told=t;
t=A/d;
err=abs((t(ii)-told(ii))/t(ii))*100;
if for ii=2:imax-1
err<=errmax
end
break
end
end

Risposte (2)

Drew Weymouth
Drew Weymouth il 8 Nov 2011
if for is not valid syntax. If you want to break out of the loop when the errors for all points are <= errmax, then the correct code is:
for ll=1:llmax
told=t;
t=A/d;
err=abs((t(ii)-told(ii))/t(ii))*100;
if max(err) <= errmax
break
end
end
If you want to break when just one point has an error <= errmax, then just replace the max with a min.
  1 Commento
Mark
Mark il 8 Nov 2011
I only want to break out of the loop when the interior of t (ii=2:imax-1) is <=errmax. The first and last points of the t are unchanging (thus having an error of 0).

Accedi per commentare.


Walter Roberson
Walter Roberson il 8 Nov 2011
for ll=1:llmax
wantbreak = false;
told=t;
t=A/d;
for ii=2:imax-1
err=abs((t(ii)-told(ii))/t(ii))*100;
wantbreak = wantbreak || err<=errmax;
if wantbreak; break; end
end
if wantbreak; break; end
end
Notice that "wantbreak" does double duty here: it selects breaking out of the inner "for" loop, and it selects breaking out of the "for" loop that is around that. There is no problem with establishing a variable that tells the outer loop that it should break.

Categorie

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

Community Treasure Hunt

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

Start Hunting!

Translated by