Find Number of Function Arguments

This example shows how to determine how many input or output arguments your function receives using nargin and nargout.

Input Arguments

Create a function in a file named addme.m that accepts up to two inputs. Identify the number of inputs with nargin.

function c = addme(a,b)

switch nargin
    case 2
        c = a + b;
    case 1
        c = a + a;
    otherwise
        c = 0;
end

Call addme with one, two, or zero input arguments.

addme(42)
ans =
    84
addme(2,4000)
ans =
        4002
addme
ans =
     0

Output Arguments

Create a new function in a file named addme2.m that can return one or two outputs (a result and its absolute value). Identify the number of requested outputs with nargout.

function [result,absResult] = addme2(a,b)

switch nargin
    case 2
        result = a + b;
    case 1
        result = a + a;
    otherwise
        result = 0;
end

if nargout > 1
   absResult = abs(result);
end

Call addme2 with one or two output arguments.

value = addme2(11,-22)
value =
    -11
[value,absValue] = addme2(11,-22)
value =
   -11

absValue =
    11

Functions return outputs in the order they are declared in the function definition.

See Also

| | |

Was this topic helpful?