How to combine multiple output from a function into 1?

11 次查看(过去 30 天)
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by