| MATLAB Function Reference | Search  Help Desk |
| varargin, varargout | Examples See Also |
Pass or return variable numbers of arguments
function varargout = foo(n) y = function bar(varargin)
function varargout = foo(n)
returns a variable number of arguments from function foo.m.
y = function bar(varargin)
accepts a variable number of arguments into function bar.m.
The varargin and varargout statements are used only inside a function M-file to contain the optional arguments to the function. Each must be declared as the last argument to a function, collecting all the inputs or outputs from that point onwards. In the declaration, varargin and varargout must be lowercase.
The function
function myplot(x,varargin)
plot(x,varargin{:})
collects all the inputs starting with the second input into the variable varargin. myplot uses the comma-separated list syntax varargin{:} to pass the optional parameters to plot. The call
myplot(sin(0:.1:1),'color',[.5 .7 .3],'linestyle',':')results in
varargin being a 1-by-4 cell array containing the values 'color','linestyle', and ':'.
The function
function [s,varargout] = mysize(x)
nout = max(nargout,1)-1;
s = size(x);
for i=1:nout, varargout(i) = {s(i)}; end
returns the size vector and, optionally, individual sizes. So
[s,rows,cols] = mysize(rand(4,5));returns
s = [4 5], rows = 4, cols = 5.
nargin Number of function arguments
nargout Number of function arguments
nargchk Check number of input arguments