How to combine multiple output from a function into 1?

13 ビュー (過去 30 日間)
Xiaohan Du
Xiaohan Du 2017 年 11 月 9 日
コメント済み: Xiaohan Du 2017 年 11 月 9 日
Hi all,
There are some functions in Matlab which gives multiple outputs, such as:
K>> [x, y, z] = ndgrid(-1:0, -1:0, -1:0)
x(:,:,1) =
-1 -1
0 0
x(:,:,2) =
-1 -1
0 0
y(:,:,1) =
-1 0
-1 0
y(:,:,2) =
-1 0
-1 0
z(:,:,1) =
-1 -1
-1 -1
z(:,:,2) =
0 0
0 0
Is there a universal way to allow this kind of functions to give only 1 output which contains all available single outputs? Something like a cell contains 3 elements which are x,y and z here? Of course if there are more outputs than 3 from ndgrid the cell elements should increase accordingly.

採用された回答

Benjamin Kraus
Benjamin Kraus 2017 年 11 月 9 日
編集済み: Benjamin Kraus 2017 年 11 月 9 日
You can only do this if you know how many outputs you are expecting. That is because MATLAB only populates the outputs you request. For example, if a function produces 3 outputs, and you only ask for 1, then MATLAB will only populate 1 output. You need some way to tell MATLAB how many outputs you are interested in, which you can only do if you know how many outputs you are expecting.
If you know how many outputs you are anticipating, you can do something like this:
numOutputs = 3;
outputs = cell(1, numOutputs);
[outputs{:}] = ndgrid(-1:0, -1:0, -1:0);
If you are not sure how many outputs to expect, you may be able to use nargout (by providing a function handle as input to nargout), but that will only work with functions that produce a fixed number of outputs (unlike ndgrid, which produces a different number of outputs depending on the number of inputs.
  1 件のコメント
Xiaohan Du
Xiaohan Du 2017 年 11 月 9 日
I do know how many outputs are there, thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by