Trouble with For loop within If statement.

1 次查看(过去 30 天)
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

回答(2 个)

Drew Weymouth
Drew Weymouth 2011-11-8
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 个评论
Mark
Mark 2011-11-8
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).

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2011-11-8
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by