Trouble with For loop within If statement.

조회 수: 1 (최근 30일)
Mark
Mark 2011년 11월 8일
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