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)
    arguments
        a (1,1) double
        b (1,1) double
        c (1,1) double = 1
        namedargs.Format (1,:) char
    end

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

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

result = fNargin(3,4)
result =

     7

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

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

   4.3021e+04

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

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

      43020.56

See Also

| |

Related Topics