nargin - Number of function input arguments - MATLAB (original) (raw)
Main Content
Number of function input arguments
Syntax
Description
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. When using an arguments validation block, the value returned bynargin
within a function is the number of positional arguments provided when the function is called. For more information, see Use nargin Functions During Argument Validation.
nargin([fun](#bsyibdf-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
.
If fun
refers to a function that uses an arguments validation block, then the returned value is the number of declared positional arguments in the function definition as a non-negative value.
Examples
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.
function c = addme(a,b) switch nargin case 2 c = a + b; case 1 c = a + a; otherwise c = 0; end end
At the command prompt, call the addme
function with two inputs.
Call the function with one input.
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'; nargin(fun)
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
.
function mynewplot(x,y,varargin) figure plot(x,y,varargin{:}) title('My New Plot') end
Query how many inputs newplot
can accept.
fx = 'mynewplot'; nargin(fx)
The minus sign indicates that the third input is varargin
. The mynewplot
function can accept an indeterminate number of additional input arguments.
Input Arguments
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
Usage notes and limitations:
- For the syntax
nargin(fun)
, iffun
is a function handle or a function name that C/C++ code generation does not support, then the generated code fornargin
returns 0. - C/C++ code generation does not support
nargin(fun)
for nested functions. Iffun
is a nested function, and no other function namedfun
exists as a local function or on the MATLABĀ® path, code generation fails.
Version History
Introduced before R2006a