Main Content

Use nargin Functions During Argument Validation

The nargin function returns the number of function input arguments given in the call to the currently executing function. When using function argument validation, the value returned by nargin within a function is the number of positional arguments provided when the function is called.

Repeating arguments are positional arguments and therefore the number of repeating arguments passed to the function when called is included in the value returned by nargin.

The value that nargin returns does not include optional input arguments that are not included in the function call. Also, nargin does not count any name-value arguments.

Use nargin to determine if optional positional arguments are passed to the function when called. For example, this function declares three positional arguments and a name-value argument. Here is how the function determines what arguments are passed when it is called.

  • nargin determines if the optional positional argument c is passed to the function with a switch block.

  • isfield determines if the name-value argument for Format is passed to the function.

function result = fNargin(a,b,c,namedargs)
        a (1,1) double
        b (1,1) double
        c (1,1) double = 1
        namedargs.Format (1,:) char

    % Function code
    switch nargin
        case  2
            result = a + b;
        case 3
            result = a^c + b^c;
    if isfield(namedargs,"Format")

In this function call, the value of nargin is 2:

result = fNargin(3,4)
result =


In this function call, the value of nargin is 3:

result = fNargin(3,4,7.62)
result =


In this function call, the value of nargin is 3:

result = fNargin(3,4,7.62,Format="bank")
result =


See Also

| |

Related Topics