Main Content

nargout

Number of function output arguments

Description

nargout returns the number of function output arguments specified in the call to the currently executing function. Use this syntax in the body of a function only.

example

nargout(fun) returns the number of outputs that appear in the fun function definition. If the function includes varargout in its definition, then nargout returns the negative of the number of outputs. For example, if function myFun declares outputs y, z, and varargout, then nargout('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.

example

Examples

collapse all

In a file named subtract.m, create a function that calculates a second return value, absdif, only if requested.

type subtract.m
function [dif,absdif] = subtract(y,x)
    dif = y-x;
    if nargout > 1
        disp('Calculating absolute value')
        absdif = abs(dif);
    end
end

At the command prompt, call the subtract function with one return value.

diff = subtract(42,13)
diff = 
29

Call the subtract function again with two return values.

[dif,absdif] = subtract(2,5)
Calculating absolute value
dif = 
-3
absdif = 
3

Determine how many outputs a function can return.

The function subtract created in the previous example has two outputs in its declaration statement (dif and absdif).

fun = @subtract;
nargout(fun)
ans = 
2

Determine how many outputs a function that uses varargout can return.

In a file named mySize.m, create a function that returns a vector of dimensions from the size function and the individual dimensions using varargout.

type mySize.m
function [sizeVector,varargout] = mySize(x)
    sizeVector = size(x);
    varargout = cell(1,nargout-1);
    for k = 1:length(varargout)
        varargout{k} = sizeVector(k);
    end
end

Query how many outputs mySize can return.

fun = 'mySize';
nargout(fun)
ans = 
-2

The minus sign indicates that the second output is varargout. The mySize function can return an indeterminate number of additional outputs.

Input Arguments

collapse all

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

Example: @rand

Example: 'sortrows'

Data Types: char | function_handle

Tips

  • When you use a function as part of an expression, such as an if statement, then MATLAB® calls the function with one output argument. Therefore, the nargout function returns 1 within expressions.

  • If you check for a nargout value of 0 within a function and you specify the value of the output, MATLAB populates ans. However, if you check nargout and do not specify a value for the output, then MATLAB does not modify ans.

Extended Capabilities

Version History

Introduced before R2006a