Azzera filtri
Azzera filtri

How to combine multiple output from a function into 1?

10 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Benjamin Kraus
Benjamin Kraus il 9 Nov 2017
Modificato: Benjamin Kraus il 9 Nov 2017
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.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by