behaviour of nargout for anonymous functions

3 views (last 30 days)
I'm struggling to understand the behaviour of nargout when used outside of a script. I have a testing function called addOne
function y = addOne(x);
with one output. I don't quite understand why nargout gives me too different outputs depending on how I pass the function handle:
>> nargout(@addOne)
ans =
>> nargout(@(x)addOne(x))
ans =
What am I overlooking?
thanks in advance!

Accepted Answer

Stephen23 on 8 Jan 2021
Edited: Stephen23 on 8 Jan 2021
You get two different answers because you are testing two different functions:
  • the function handle to addOne
  • an anonymous function (which happens to call some other function/s inside it, but these are irrelevant).
Testing the simple function handle returns the number of output arguments supported by that function:
fb = @sort;
ans = 2
However nargout only measures the output of the anonymous function itself, not any functions that happen to be called inside it. And anonymous functions attempt to return as many output arguments as are requested when the code is evaluated, i.e. the anonymous function syntax supports any number of output arguments, which the nargout documentation tells us is indicated by a negative output value. For example:
f0 = @(x)disp(x); % DISP has no outputs
f1 = @(x)sqrt(x); % SQRT has one output
f2 = @(x)sort(X); % SORT has two outputs
fn = @(x)ndgrid(x); % NDGRID has any number of outputs
ans = -1
ans = -1
ans = -1
ans = -1
These all return -1 because nargout can only check the anonymous function itself, NOT any functions that happen to be called inside it!

More Answers (0)


Find more on Operators and Elementary Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by