How to Use return in MATLAB: Syntax and Examples
In MATLAB, use the
return statement to immediately exit a function and return control to the calling function or command window. Place return anywhere inside a function to stop execution at that point.Syntax
The return statement has a simple syntax with no arguments. It is used inside a function to stop execution and return control immediately.
- return: Exits the current function immediately.
matlab
function exampleReturn() disp('Start of function') return disp('This line will not run') end
Example
This example shows how return stops the function early. The message after return is not displayed.
matlab
function testReturn() disp('Before return') return disp('After return - will not display') end testReturn()
Output
Before return
Common Pitfalls
Common mistakes include using return outside functions, which causes errors, or expecting return to return a value (it does not). Also, placing code after return means that code will never run.
matlab
function wrongReturn() disp('Start') return % Incorrect: return does not accept values disp('This will never run') end % Correct usage: function correctReturn() disp('Start') return disp('This will never run') end
Quick Reference
Tips for using return in MATLAB:
- Use
returnonly inside functions. returnstops function execution immediately.returndoes not return values; use output variables instead.- Code after
returnis ignored.
Key Takeaways
Use
return inside functions to exit early and stop execution.return does not return values; use output variables for that.Code after
return will not run, so place it carefully.Do not use
return outside functions; it causes errors.