Programming Previous page   Next Page

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 is an example function that accepts any number of two-element vectors and draws a line to connect them:

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 preceding code, the indexing expression {i} accesses the nth 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 shown in the earlier example:

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 Cell Arrays.

To call testvar2, type

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:

Previous page  Function Arguments Passing Optional Arguments to Nested Functions Next page

© 1994-2005 The MathWorks, Inc.