Documentation Center

  • Trial Software
  • Product Updates
我们为许可用户提供了部分翻译好的中文文档。您只需登录便可查阅这些文档

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

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

More About

expand all

Tips

  • 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')
    end

See Also

| | | | |

Was this topic helpful?