How to combine multiple output from a function into 1?

조회 수: 23 (최근 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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by