Documentation Center

  • Trial Software
  • Product Updates


Number of function output arguments




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


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


expand all

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);

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';
ans =

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);

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

fx = 'mysize';
ans =

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

More About

expand all


  • When you use a function as part of an expression, MATLAB® calls the function with one output argument, so nargout within the function returns 1. For example, given the following if statement and the subtract function defined in the Examples section, the value of nargout within the subtract function is 1.

    a = 1; b = 2;
    if subtract(a,b) < 0
       disp('Result is negative')

See Also

| | | | |

Was this topic helpful?