Get maximum number of outputs from anonymous function

조회 수: 8 (최근 30일)
Luca Amerio
Luca Amerio 2017년 10월 20일
댓글: Stephen23 2017년 10월 20일
Hi everybody. I would like to call a function from within another function. The problem is that i don't know a-priori the number of output variable of the function i'm calling. I can evaluate it with nargout, but once i've done it, how can I call the function with that number of outputs?
function varargout = myfunction(fun, varargin)
% Do some stuff here
funName = func2str(fun);
maxnargout = nargout(funName);
[??] = fun(varargin{:})
% Do some stuff here
Using "eval" I could do something like
eval(['[ varargout{1}' sprintf(', varargout{%i}',2:maxnargout ) '] = fun(varargin{:})'])
but it is utterly awful!!!!

채택된 답변

Cam Salzberger
Cam Salzberger 2017년 10월 20일
Hello Luca,
That's a somewhat tricky one, and I agree that going the "eval" route is not the best way. You can get around it using some tricks with cell arrays. Also, I believe that you can use nargout directly on the function handle.
f = @max;
x = rand(3);
results = cell(1, nargout(f));
[results{:}] = f(x);
-Cam
  댓글 수: 2
Luca Amerio
Luca Amerio 2017년 10월 20일
Wow! It was rather trivial! Didn't think to use the typical [cell{:}] syntax for the output.
Thank you very much
Stephen23
Stephen23 2017년 10월 20일
@Luca Amerio: you can use comma-separated lists anywhere that you would use a comma-separated list of variables. Very handy!

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

추가 답변 (1개)

Guillaume
Guillaume 2017년 10월 20일
Use the conversion of comma-separated lists to cell array (or structure):
maxnargout = nargout(funName);
out = cell(1, maxnargout);
[out{:}] = fun(varargin{:});
Or if the outputs of fun are meant to go into the varargout of myfunction, then replace out by varargout.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by