nargout - Number of function output arguments - MATLAB (original) (raw)

Number of function output arguments

Syntax

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](#bsyib3%5F-1-fun)) returns the number of outputs that appear in the fun function definition. If the function includes varargout in its definition, thennargout returns the negative of the number of outputs. For example, if function myFun declares outputs y,z, and varargout, thennargout('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.

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.

Call the subtract function again with two return values.

[dif,absdif] = subtract(2,5)

Calculating absolute value

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)

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.

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)

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

Extended Capabilities

expand all

Usage notes and limitations:

Version History

Introduced before R2006a