Functions can accept variable numbers of inputs and outputs using a single function signature. MATLAB® provides several techniques for checking the number, type, size, and other aspects of the inputs to ensure functions perform as intended and to provide useful error messages in cases where inputs are not valid.
Find Number of Function Arguments
Use nargin
and nargout
to
determine how many input or output arguments your function receives.
Support Variable Number of Inputs
Define a function that accepts a variable number of
input arguments using varargin
. The varargin
argument
is a cell array that contains the function inputs, where each input
is in its own cell.
Support Variable Number of Outputs
Define a function that returns a variable number of
output arguments using varargout
. Output varargout
is
a cell array that contains the function outputs, where each output
is in its own cell.
Validate Number of Function Arguments
Check if your custom function receives a valid number
of input or output arguments. MATLAB performs some argument checks
automatically. For other cases, you can use narginchk
or nargoutchk
.
Argument Checking in Nested Functions
There are special considerations for using varargin
, varargout
, nargin
,
and nargout
with nested functions.
If your function accepts a predefined set of inputs, but does not use all the
inputs, use the tilde (~
) operator to ignore them in your
function definition.
This example shows how to request specific outputs from a function.
Choose a technique for checking the validity of input arguments.
Declare input argument class and size and enforce restrictions on argument values.
Check Function Inputs with validateattributes
This example shows how to verify that the inputs to
your function conform to a set of requirements using the validateattributes
function.
Define required and optional inputs, assign defaults to optional inputs, and validate all inputs to a custom function using the Input Parser.