behaviour of nargout for anonymous functions

조회 수: 4 (최근 30일)
Arabarra
Arabarra 2021년 1월 8일
편집: Simon 2023년 8월 29일
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);
y=x+1;
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 =
1
>> nargout(@(x)addOne(x))
ans =
-1
What am I overlooking?
thanks in advance!
Daniel

채택된 답변

Stephen23
Stephen23 2021년 1월 8일
편집: Stephen23 2021년 1월 8일
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;
nargout(fb)
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
nargout(f0)
ans = -1
nargout(f1)
ans = -1
nargout(f2)
ans = -1
nargout(fn)
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!
  댓글 수: 1
Simon
Simon 2023년 8월 29일
편집: Simon 2023년 8월 29일
Thanks for the explanation. I just now had the same question. And
nargout(@(x)x) % -1

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by