Starting a Loop over again

If I am in a while/end loop and I find that I have a mistake and want to get out of the loop and start the loop over again, how do I do it?
I have tried break but that gets me out of the loop and positions me to go on the next part of the script. Instead, I want to go back and start the loop over again.
Thanks,
Dave

답변 (1개)

Walter Roberson
Walter Roberson 2012년 12월 20일
편집: Walter Roberson 2012년 12월 20일

0 개 추천

continue
as in
c = 0;
while c <= 100
I_detected_an_error = rand() < 0.07;
if I_detected_an_error
disp('LART!')
continue;
end
c = c + 1;
end

댓글 수: 4

David Koenig
David Koenig 2012년 12월 20일
편집: Walter Roberson 2012년 12월 20일
Thanks for the response.
I had to use
c = 0;
while c <= 100
ii = rand() < 0.07;
if ii
disp('LART!')
continue;
end
c = c + 1;
end
to get it to run. I guess I_detected_an_error caused my Matlab to choke.
In any case I don't see how it solves my problem but that is likely because I just don't understand. To address my problem in the meantime, I put the algorithm that I wish to repeat into a function with a error return code. If there is an error I call the function again...it's crude but it will do.
Thanks again.
Dave
I had a typo in a variable name, oops.
Try this to make it more obvious that the rest of the loop body is being skipped but the loop continues:
c = 1;
while c <= 20
I_detected_an_error = rand() < 0.07;
if I_detected_an_error
disp('LART!')
continue;
else
disp('No LART!')
end
c = c + 1;
end
You might have to run more than once to see a LART.
The output you get will have "No LART" 20 times, with a variable number of LART mixed in. If the rest of the body of the loop was being executed after the "continue" then you would get exactly 20 outputs rather than exactly 20 "No LART". The "continue" is popping it back to the beginning of the loop.
Image Analyst
Image Analyst 2012년 12월 20일
I think you need to set c = 1 just before the continue if you really want to start the loop all over again from the beginning, instead of just continuing with the next iteration.
Walter Roberson
Walter Roberson 2012년 12월 20일
Ah, yes, that is a plausible interpretation of the question. Not what I would have guessed, but plausible.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

태그

질문:

2012년 12월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by