Main Content

nargout

Number of function output arguments

Description

example

nargoutreturns 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 thefunfunction definition. If the function includesvarargoutin its definition, thennargoutreturns the negative of the number of outputs. For example, if functionmyFundeclares outputsy,z, andvarargout, thennargout ('myFun')returns-3.

Examples

collapse all

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

typesubtract.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 thesubtractfunction with one return value.

diff = subtract(42,13)
diff = 29

Call thesubtractfunction 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 functionsubtract在上一步中创建example has two outputs in its declaration statement (difandabsdif).

有趣的=@subtract; nargout(fun)
ans = 2

Determine how many outputs a function that usesvarargoutcan return.

In a file namedmySize.m, create a function that returns a vector of dimensions from thesizefunction and the individual dimensions usingvarargout.

typemySize.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 outputsmySizecan return.

有趣的='mySize'; nargout(fun)
ans = -2

The minus sign indicates that the second output isvarargout. ThemySizefunction can return an indeterminate number of additional outputs.

Input Arguments

collapse all

Function for whichnargoutreturns 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 anifstatement, then MATLAB®calls the function with one output argument. Therefore, thenargoutfunction returns1within expressions.

  • If you check for anargoutvalue of 0 within a function and you specify the value of the output, MATLAB populatesans. However, if you checknargoutand do not specify a value for the output, then MATLAB does not modifyans.

Extended Capabilities

Version History

Introduced before R2006a