Using the C Math Library | ![]() ![]() |
Variable Input Arguments
Some MATLAB functions accept any number of input arguments. In MATLAB these functions are called varargin
functions. When the variable varargin
appears as the last input argument in the definition of a MATLAB function, you can pass any number of input arguments to the function, starting at that position in the argument list.
MATLAB takes the arguments you pass and stores them in a cell array, which can hold any size or kind of data. The varargin
function then treats the elements of that cell array exactly as if they were arguments passed to the function.
Whenever you see ...
(an ellipsis) at the end of the input argument list in a MATLAB syntax description, the function is a varargin
function. For example, the syntax for the MATLAB function cat
includes the following specification in the online MATLAB Function Reference.
B = cat(dim,A1,A2,A3,A4,...)
cat
accepts any number of arguments. The dim
and A1
arguments to cat
are required. You then concatenate any number of additional arrays along the dimension dim
. For example, this call concatenates six arrays along the second dimension.
B = cat(2,A1,A2,A3,A4,A5,A6)
The C language supports functions that accept variable-length argument lists. MATLAB varargin
functions translate easily into these functions. The variable number of arguments are always specified at the end of the argument list and are indicated in the function prototype as an ellipsis (...
). For example, the prototype for the mlfCat()
function in the MATLAB C Math Library is
mxArray *mlfCat(mxArray *dim, mxArray *A1, ...);
Though C uses its own mechanism, different from cell arrays, to process variable-length argument lists, the translation from a call to a MATLAB varargin
function to a call to the MATLAB C Math Library function is straightforward. You invoke mlfCat()
like this
mlfAssign(&B, mlfCat(mlfScalar(2),A1,A2,A3,A4,A5,A6,NULL));
where B
is an mxArray *
variable, initialized to NULL
. The six A
matrices are also mxArray *
variables.
Pure Varargin Functions
Some MATLAB functions take a varargin
argument as their only input argument, and are therefore called pure varargin
functions. For example,
function [output_arg1] = Example_Pure_Varargin(varargin)
declares a pure varargin
function in MATLAB.
Because the C language requires at least one explicit argument in the definition of a varargin
function, this pure varargin
function translates to
mxArray *Example_Pure_Varargin(mxArray *input_arg1, ...);
where input_arg1
is the first of the varargin
parameters even though it is an explicit argument.
![]() | Optional Input and Output Arguments | Variable Output Arguments | ![]() |