Skip to Main Content Skip to Search
Product Documentation

nargout - Number of function output arguments

Syntax

nargout
nargout(fx)

Description

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

nargout(fx) returns the number of outputs that appear in the definition statement of function fx. If the function includes varargout in its definition, then nargout returns the negative of the number of outputs. For example, if function foo declares outputs a, b, and varargout, then nargout('foo') returns -3.

Input Arguments

fx

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

Examples

Outputs for Current Function

Create a function in a file named subtract.m that calculates a second return value only when requested.

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

Outputs Defined for a Function

Determine how many outputs a function can return.

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

fx = 'subtract';
nargout(fx)
ans =
     2

Function with varargout Output

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

Define a function in a file named mysize.m 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

At the command line, query how many outputs mysize can return.

fx = 'mysize';
nargout(fx)
ans =
    -2

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

Tips

See Also

inputname | nargin | narginchk | nargoutchk | varargin | varargout

  


» Learn more
» Download free kit
» Get trial software

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS