How to get multiple outputs of a function in a vector?

纵饮孤独 提交于 2019-12-23 12:17:44

问题


Say I have a function whose outputs are two reals a and b

[a,b]=function(c)

I'd like to get all the outputs in a vector v. v=function(c) doesn't do what I want, v is 'a' only. Of course here I could do v=[a,b]. But the function in question is ind2sub for a N-D array so it gives n outputs that I'd like to have in a vector directly.

Is there a way to do it? Thanks very much!


回答1:


You can use a cell array and a comma-separated list like so:

X = cell(N, 1);
[X{:}] = function(C);

The syntax X{:} is in fact expanded to [X{1}, X{2}, ...], which provides a valid sink for your function. As a result, each output variable will be stored in a different cell in X.

If each output variable is a scalar, you can flatten out the cell array into a vector by using yet another comma-separated list expansion:

v = [X{:}];


来源:https://stackoverflow.com/questions/16943871/how-to-get-multiple-outputs-of-a-function-in-a-vector

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