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
댓글 수: 0
답변 (2개)
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.
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!