Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

我们为许可用户提供了部分翻译好的中文文档。您只需登录便可查阅这些文档

nargin

Number of function input arguments

Syntax

nargin
nargin(fx)

Description

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

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

Input Arguments

fx

Either a function handle or a character vector in single quotes that specifies the name of a function.

Examples

collapse all

Create a function in a file named addme.m that accepts up to two inputs, and 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

Determine how many inputs a function can accept.

The function addme created in the previous example has two inputs in its declaration statement (a and b).

fx = 'addme';
nargin(fx)
ans =
     2

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

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

function mynewplot(x,y,varargin)
   figure
   plot(x,y,varargin{:})
   title('My New Plot')

At the command line, query how many inputs newplot can accept.

fx = 'mynewplot';
nargin(fx)
ans =
    -3

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

Introduced before R2006a


Was this topic helpful?