How to get all outputs (MatLab)?

耗尽温柔 提交于 2021-01-27 06:29:30

问题


Suppose I have a function that gives out unknown number of output arguments (it depends on input,thus change through the loops). How to get all of them?

nargout doesn't help as the function uses varargout (the result is -1)

And of course I can't rewrite the function, otherwise the question wouldn't arise :- )


回答1:


Well, thanks to all partisipated in discussion. Summing up, it seems the problem has no general solution, because MatLab itself estimates the number of desired outputs before the function call to use inside it. Three cases can be pointed out though:

1) The funcrion doesn't have varargout in definition, thus nOut=nargout(@fcn) returns positive number.

Then nOut is an actual number of outputs and we can use a cell array and a column list trick.

X=cell(1,nOut);
[X{:}]=fcn(inputs);

2) The funcrion has varargout in definition, thus nOut=nargout(@fcn) returns negative number. However some correlation with inputs can be found (like length(varargin)=length(varargout)).

Then we can calculate the resulting nOut from inputs and perform the above column list trick.

3) You know the fcn developer.

Ask him fot assistance. For example to make the function's output to be a cell array.




回答2:


One of ways I usually use in this case is to store all outputs in a cell array inside the function. Getting the cell array outside the function's body, you might investigate its length and other properties.




回答3:


Here is how you could deal with the problem in general. I didn't mention this solution earlier because... it is horrible.

Suppose a function can have 1 or 2 output arguments:

try 
  [a, b] = f(x)
catch
  a = f(x)
end

Of course it is possible to do this for any number of output arguments, but you really don't want to.



来源:https://stackoverflow.com/questions/24657164/how-to-get-all-outputs-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!