Support Variable Number of Outputs
This example shows how to define a function that returns a variable number of output arguments
using varargout. Output varargout is a cell array that contains the function outputs, where each
output is in its own cell.
Create a function in a file named magicfill.m that assigns a magic square to each requested
output.
function varargout = magicfill
nOutputs = nargout;
varargout = cell(1,nOutputs);
for k = 1:nOutputs
varargout{k} = magic(k);
end
Indexing with curly braces {} updates the contents of a cell.
Call magicfill and request three outputs.
[first,second,third] = magicfill
first =
1
second =
1
3
4
2
third =
8
1
6
3
5
7
4
9
2
MATLAB assigns values to the outputs according to their order in the varargout array. For example,
first == varargout{1}.
You can use varargout alone in an output argument list, or at the end of the list of outputs, such as
function [x,y,varargout] = myfunction(a,b)
In this case, varargout{1} corresponds to the third output that the function returns, and nargout
returns length(varargout) + 2.
See Also
nargout | varargout
Related Examples
•
“Access Data in Cell Array” on page 12-5
More About
•
“Checking Number of Arguments in Nested Functions” on page 21-8
Support Variable Number of Outputs
21-5
Précédent

- 761/1450

Suivant