| Contents | Index |
nargout
nargout(fx)
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.
fx |
Either a function handle or a string in single quotes that specifies the name of a 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
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 =
2Determine 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 =
-2The minus sign indicates that the second output is varargout. The mysize function can return an indeterminate number of additional outputs.
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
inputname | nargin | narginchk | nargoutchk | varargin | varargout
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |