MATLAB: “Return” and “continue” functions!

continuereturn

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

Best Answer

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.
Related Question