0
0
MATLABdata~5 mins

Multiple outputs in MATLAB

Choose your learning style9 modes available
Introduction
Sometimes you want a function to give back more than one answer at the same time. Multiple outputs let you do that easily.
When you want a function to return both the result and some extra information about it.
When you need to get several related values from one calculation.
When you want to avoid running the same code multiple times to get different results.
When you want to keep your code clean by grouping outputs together.
When you want to return both a value and a status or error code from a function.
Syntax
MATLAB
function [out1, out2, ..., outN] = functionName(inputs)
    % Your code here
end
Use square brackets [ ] to list multiple outputs separated by commas.
Call the function with the same number of output variables to get each result.
Examples
This function returns two outputs: the sum and the difference of two numbers.
MATLAB
function [sum, diff] = addAndSubtract(a, b)
    sum = a + b;
    diff = a - b;
end
Calling the function with two output variables captures both results.
MATLAB
[s, d] = addAndSubtract(5, 3)
% s will be 8, d will be 2
You can choose to get only the first output if you want.
MATLAB
[onlySum] = addAndSubtract(5, 3)
% onlySum will be 8, difference is ignored
Sample Program
This program defines a function that returns both the area and perimeter of a rectangle. Then it calls the function and prints both results.
MATLAB
function [area, perimeter] = rectangleProperties(length, width)
    area = length * width;
    perimeter = 2 * (length + width);
end

% Call the function
[lArea, lPerimeter] = rectangleProperties(4, 7);

% Display the results
fprintf('Area: %d\n', lArea);
fprintf('Perimeter: %d\n', lPerimeter);
OutputSuccess
Important Notes
If you call a function with fewer output variables than it returns, MATLAB ignores the extra outputs.
If you call a function with more output variables than it returns, MATLAB gives an error.
Use multiple outputs to keep your code efficient and organized.
Summary
Multiple outputs let a function return several values at once.
Use square brackets to list outputs in the function definition.
Call the function with matching output variables to get each result.