Programming and Data Types |
Passing Variable Numbers of Arguments
The varargin
and varargout
functions let you pass any number of inputs or return any number of outputs to a function. This section describes how to use these functions and also covers:
MATLAB packs all specified input arguments into a cell array, a special kind of MATLAB array that consists of cells instead of array elements. Each cell can hold any size or kind of data - one might hold a vector of numeric data, another in the same array might hold an array of string data, and so on. For output arguments, your function code must pack them into a cell array so that MATLAB can return the arguments to the caller.
Here's an example function that accepts any number of two-element vectors and draws a line to connect them.
function testvar(varargin) for k = 1:length(varargin) x(k) = varargin{k}(1); % Cell array indexing y(k) = varargin{k}(2); end xmin = min(0,min(x)); ymin = min(0,min(y)); axis([xmin fix(max(x))+3 ymin fix(max(y))+3]) plot(x,y)
Coded this way, the testvar
function works with various input lists; for example,
Unpacking varargin Contents
Because varargin
contains all the input arguments in a cell array, it's necessary to use cell array indexing to extract the data. For example,
Cell array indexing has two subscript components:
In the code above, the indexing expression {i}
accesses the i
'th cell of varargin
. The expression (2)
represents the second element of the cell contents.
Packing varargout Contents
When allowing any number of output arguments, you must pack all of the output into the varargout
cell array. Use nargout
to determine how many output arguments the function is called with. For example, this code accepts a two-column input array, where the first column represents a set of x
coordinates and the second represents y
coordinates. It breaks the array into separate [xi yi]
vectors that you can pass into the testvar
function on the previous page.
function [varargout] = testvar2(arrayin) for k = 1:nargout varargout{k} = arrayin(k,:) % Cell array assignment end
The assignment statement inside the for
loop uses cell array assignment syntax. The left side of the statement, the cell array, is indexed using curly braces to indicate that the data goes inside a cell. For complete information on cell array assignment, see the Structures and Cell Arrays section.
varargin and varargout in Argument Lists
varargin
or varargout
must appear last in the argument list, following any required input or output variables. That is, the function call must specify the required arguments first. For example, these function declaration lines show the correct placement of varargin
and varargout
.
Checking the Number of Function Arguments | Subfunctions |