Skip to content

MATLAB - Return Statement

In MATLAB, the return statement provides a mechanism to terminate the execution of a function or script prematurely and pass control back to the calling function or the command window. It is a control flow statement, not a value-passing mechanism.

It’s crucial to understand that a MATLAB function returns values based on its definition, not explicitly because of the return keyword. A function returns values when its execution reaches the end statement.

function output = myFunc(input)
% Calculations happen here
output = input * 2;
% The value of 'output' is returned when the function ends.
end % Execution finishes, control returns to caller

The primary purpose of the return statement is to exit the function early, typically from within a conditional block.

function [out1, out2] = functionName(in1, in2)
% Function body
if (some_condition)
% An early exit is needed
return;
end
% More code here if the condition is false
out1 = ...;
out2 = ...;
end

When return is executed, the function immediately stops. Any code within the function after the return statement is not executed. The function will return the current values of the output arguments as they were at that moment.

Example 1: Input Validation with a Guard Clause

Section titled “Example 1: Input Validation with a Guard Clause”

A common and excellent use for return is to validate inputs at the beginning of a function. This is known as a “guard clause”.

function result = calculateRatio(x, y)
% Guard Clause: Check for invalid input 'y'
if y == 0
warning('Division by zero is not possible. Returning NaN.');
result = NaN; % Assign a placeholder value
return; % Exit the function immediately
end
% This code only runs if the guard clause is passed
disp('Calculation proceeding...');
result = x / y;
end

Let’s call this function from the command window:

val1 = calculateRatio(10, 2)
Calculation proceeding...
val1 =
5
val2 = calculateRatio(10, 0)
Warning: Division by zero is not possible. Returning NaN.
val2 =
NaN

Notice how the disp('Calculation proceeding...') line was skipped in the second call.

Example 2: Returning Multiple Values with an Early Exit

Section titled “Example 2: Returning Multiple Values with an Early Exit”

If a function is supposed to return multiple values, they should be assigned before an early return is called.

function [stats, success] = processData(data)
% Check if input data is empty
if isempty(data)
disp('Input data is empty. Cannot compute stats.');
stats = struct(); % Return an empty struct
success = false; % Indicate failure
return; % Early exit
end
% If data is valid, compute statistics
stats.mean = mean(data);
stats.std_dev = std(data);
stats.min = min(data);
stats.max = max(data);
success = true;
end

Executing in the command window demonstrates the control flow:

sampleData = [1, 5, 2, 8, 4];
[s, ok] = processData(sampleData)
s =
struct with fields:
mean: 4
std_dev: 2.7386
min: 1
max: 8
ok =
logical
1
[s_empty, ok_empty] = processData([])
Input data is empty. Cannot compute stats.
s_empty =
struct with no fields.
ok_empty =
logical
0
  • Do Use return for Guard Clauses: Checking inputs at the start of a function makes your code cleaner and more robust than nesting your main logic inside a large if-else block.
  • Don’t Place return at the End: A return statement right before the end keyword is redundant and adds clutter. The function will return anyway.
  • Initialize Output Arguments: If there’s a possibility of an early exit, it’s good practice to initialize your output arguments to default or error-state values (e.g., NaN, false, []). This ensures the function always returns a value of the expected type.
  • return vs. error: If an input makes it impossible for the function to continue, it is often better to throw an error with the error('Descriptive message') function. This halts execution completely and is clearer than returning a special value that the calling code then has to check.