Main Content

Checking Number of Arguments in Nested Functions

This topic explains special considerations for using varargin, varargout, nargin, and nargout with nested functions.

varargin and varargout allow you to create functions that accept variable numbers of input or output arguments. Although varargin and varargout look like function names, they refer to variables, not functions. This is significant because nested functions share the workspaces of the functions that contain them.

If you do not use varargin or varargout in the declaration of a nested function, then varargin or varargout within the nested function refers to the arguments of an outer function.

For example, create a function in a file named showArgs.m that uses varargin and has two nested functions, one that uses varargin and one that does not.

function showArgs(varargin)

    function nested1(a,b)
        disp('nested1: Contents of varargin{1}')

    function nested2(varargin)
        disp('nested2: Contents of varargin{1}')


Call the function and compare the contents of varargin{1} in the two nested functions.

nested1: Contents of varargin{1}

nested2: Contents of varargin{1}

On the other hand, nargin and nargout are functions. Within any function, including nested functions, calls to nargin or nargout return the number of arguments for that function. If a nested function requires the value of nargin or nargout from an outer function, pass the value to the nested function.

For example, create a function in a file named showNumArgs.m that passes the number of input arguments from the primary (parent) function to a nested function.

function showNumArgs(varargin)

disp(['Number of inputs to showNumArgs: ',int2str(nargin)]);

    function nestedFx(n,varargin)
        disp(['Number of inputs to nestedFx: ',int2str(nargin)]);
        disp(['Number of inputs to its parent: ',int2str(n)]);


Call showNumArgs and compare the output of nargin in the parent and nested functions.

Number of inputs to showNumArgs: 2
Number of inputs to nestedFx: 4
Number of inputs to its parent: 2

See Also

| | |