"Return" and "continue" functions!
조회 수: 299 (최근 30일)
이전 댓글 표시
Hello MATLAB experts :)
I have not got the concept of "return" and "continue" functions in MATLAB. I went through the help but the examples were not so comprehensive for me. Please could you kindly explain them with a nice example per each?
Have a nice WE,
Mehdi
댓글 수: 0
채택된 답변
Dr. Seis
2012년 10월 19일
편집: Dr. Seis
2012년 10월 19일
Continue example:
function VALUE = somefunction
while SOME_CONDITION
DO_THIS;
if SOME_OTHER_CONDITION
continue;
end
DO_THAT
end
VALUE = SOMETHING;
If SOME_OTHER_CONDITION is true, then continue will essentially skip any remaining statements (i.e., DO_THIS will be executed, but DO_THAT will be skipped) in the loop and re-enter the loop provided SOME_CONDITION is still true. If SOME_OTHER_CONDITION is false, then continue will not be encountered and will execute both DO_THIS and DO_THAT for that loop iteration.
Return example:
function VALUE = somefunction
while SOME_CONDITION
DO_THIS;
if SOME_OTHER_CONDITION
VALUE = SOMETHING;
return;
end
DO_THAT
end
DO_SOMETHING_ELSE;
If SOME_OTHER_CONDITION is true, then return will not only skip any remaining statements (i.e., DO_THIS will be executed, but DO_THAT will be skipped) but it will also completely exit the loop. return will also exit the function (skipping DO_SOMETHING_ELSE) and return VALUE. If SOME_OTHER_CONDITION is false, then return will not be encountered and will execute both DO_THIS and DO_THAT for that loop iteration.
댓글 수: 8
추가 답변 (1개)
Danupon Subanapong
2018년 11월 16일
Very nice explanation, but I have a question. Please see below.
1) Using continue
function VALUE = somefunction
while SOME_CONDITION
DO_THIS;
if SOME_OTHER_CONDITION
continue;
end
DO_THAT
end
VALUE = SOMETHING;
2) No continue just if and ifelse
function VALUE = somefunction
while SOME_CONDITION
DO_THIS;
if ~SOME_OTHER_CONDITION
DO_THAT
else
end
end
VALUE = SOMETHING;
Are these two methods giving the same result?
댓글 수: 2
darova
2020년 4월 21일
No
function VALUE = somefunction
while SOME_CONDITION
DO_THIS;
if SOME_OTHER_CONDITION
continue;
end
DO_THAT1
DO_THAT2
DO_THAT3
end
VALUE = SOMETHING;
Ii SOME_OTHER_CONDITION is true then continue skips iteration (all DO_THAT will not be executed)
참고 항목
카테고리
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!