How to Return Multiple Values in MATLAB Functions
In MATLAB, you can return multiple values from a function by listing them as multiple output arguments in square brackets, like
[out1, out2] = functionName(inputs). Inside the function, assign values to each output variable in order. This allows you to get several results from one function call.Syntax
The basic syntax to return multiple values from a MATLAB function is:
[output1, output2, ..., outputN] = functionName(input1, input2, ...)Here:
output1, output2, ..., outputNare the variables that will receive the returned values.functionNameis the name of your function.input1, input2, ...are the inputs to the function.
Inside the function, you assign values to each output variable in the order they are declared.
matlab
function [a, b] = exampleFunction(x) a = x + 1; b = x * 2; end
Example
This example shows a function that returns two values: the square and the cube of the input number.
matlab
function [square, cube] = powers(num) square = num^2; cube = num^3; end % Call the function [sq, cb] = powers(3); % Display the results fprintf('Square: %d\n', sq); fprintf('Cube: %d\n', cb);
Output
Square: 9
Cube: 27
Common Pitfalls
Common mistakes when returning multiple values in MATLAB include:
- Not using square brackets
[]around multiple output variables when calling the function. - Assigning fewer output variables than the function returns, which can cause errors or missing values.
- Not matching the order of outputs in the function definition and the call.
Always use square brackets to capture multiple outputs and ensure the number of outputs matches.
matlab
function [x, y] = wrongExample(a) x = a + 10; y = a - 5; end % Wrong way (missing brackets): [x, y] = wrongExample(7); % Correct way % Right way: [x, y] = wrongExample(7);
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Multiple outputs | Use square brackets to list outputs | [out1, out2] = func(inputs) |
| Assign outputs | Assign values inside function in order | out1 = val1; out2 = val2; |
| Call function | Use brackets to capture multiple outputs | [a, b] = func(x); |
| Output order | Order of outputs matters | Match function and call order |
Key Takeaways
Use square brackets to return and capture multiple values in MATLAB functions.
Assign each output variable inside the function in the order declared.
Match the number and order of outputs between function definition and call.
Always use brackets when calling functions that return multiple values.
Avoid missing or extra output variables to prevent errors.