This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Number of function input arguments





nargin returns the number of function input arguments given in the call to the currently executing function. Use this syntax in the body of a function only.


nargin(fun) returns the number of input arguments that appear in the fun function definition. If the function includes varargin in its definition, then nargin returns the negative of the number of inputs. For example, if function myFun declares inputs a, b, and varargin, then nargin('myFun') returns -3.


collapse all

In a file named addme.m, create a function that accepts up to two inputs. Use nargin in the body of the function to determine the number of inputs.

type addme.m
function c = addme(a,b)
    switch nargin
        case 2
            c = a + b;
        case 1
            c = a + a;
            c = 0;

At the command prompt, call the addme function with two inputs.

c = addme(13,42)
c = 55

Call the function with one input.

c = addme(13)
c = 26

Determine how many inputs a function accepts.

The function addme created in the previous example, has two inputs in its declaration statement (a and b). Define the name of the function as a character vector and use it as input for nargin.

fun = 'addme';
ans = 2

Determine how many inputs a function that uses varargin can accept.

In a file named mynewplot.m, create a function that accepts numeric inputs x and y and any number of additional plot inputs using varargin.

type mynewplot.m
function mynewplot(x,y,varargin)
    title('My New Plot')

Query how many inputs newplot can accept.

fx = 'mynewplot';
ans = -3

The minus sign indicates that the third input is varargin. The mynewplot function can accept an indeterminate number of additional input arguments.

Input Arguments

collapse all

Function for which nargin returns the number of input arguments from its definition, specified as a function handle, a character vector, or a string scalar.

Example: @cos

Example: 'plot'

Data Types: char | function_handle

Extended Capabilities

Introduced before R2006a

Was this topic helpful?