Trouble with For loop within If statement.

1 visualización (últimos 30 días)
Mark
Mark el 8 de Nov. de 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

Respuestas (2)

Drew Weymouth
Drew Weymouth el 8 de Nov. de 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 comentario
Mark
Mark el 8 de Nov. de 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).

Iniciar sesión para comentar.


Walter Roberson
Walter Roberson el 8 de Nov. de 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.

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