Use nargin Functions During Argument Validation - MATLAB & Simulink (original) (raw)

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 bynargin.

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.

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 is2:

In this function call, the value of nargin is3:

result = fNargin(3,4,7.62)

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

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

See Also

nargin | arguments | namedargs2cell

Topics