varargout - Variable-length output argument list - MATLAB (original) (raw)
Main Content
Variable-length output argument list
Syntax
Description
varargout
is an output variable in a function definition statement that enables the function to return any number of output arguments. Specify varargout
using lowercase characters, and include it as the last output argument after any explicitly declared outputs.
When the function executes, varargout
is a 1-by-N cell array, where N is the number of outputs requested after the explicitly declared outputs. Inside of a function,varargout
is an uninitialized variable and is not preallocated.
Examples
Define a function in a file named returnVariableNumOutputs.m
that returns an output size vector s
and a variable number of additional outputs.
type returnVariableNumOutputs
function [s,varargout] = returnVariableNumOutputs(x) nout = max(nargout,1) - 1; s = size(x); for k = 1:nout varargout{k} = s(k); end end
Output s
contains the dimensions of the input array x
. Additional outputs correspond to the individual dimensions within s
.
Call the function with a three-dimensional array and request three outputs.
A = rand(4,5,2); [s,rows,cols] = returnVariableNumOutputs(A)
Call the function again with a four-dimensional array and request four outputs. This time, the function does not return the individual fourth dimension.
A = zeros(1,4,5,2); [s,dim1,dim2,dim3] = returnVariableNumOutputs(A)
Call the function once more on A
and request one output. Now the function returns the dimensions of A
and not varargout
.
s = returnVariableNumOutputs(A)
Define a function in a file named variableNumInputAndOutput.m
that accepts a variable number of inputs and outputs.
type variableNumInputAndOutput
function varargout = variableNumInputAndOutput(varargin) disp(['Number of provided inputs: ' num2str(length(varargin))]) disp(['Number of requested outputs: ' num2str(nargout)])
for k = 1:nargout
varargout{k} = k;
end
end
Call the function with two inputs and three outputs.
[d,g,p] = variableNumInputAndOutput(6,'Nexus')
Number of provided inputs: 2 Number of requested outputs: 3
Call the function again with no inputs or outputs.
variableNumInputAndOutput
Number of provided inputs: 0 Number of requested outputs: 0
Extended Capabilities
Usage notes and limitations:
- For code generation, to use
varargout
in an entry-point (top-level) function, you must specify the number of output parameters by using thecodegen -nargout
syntax. - The index into
varargout
must be a compile-time constant.
Version History
Introduced before R2006a