How to redirect function output arguments to a cell array

조회 수: 23 (최근 30일)
Lane
Lane 2021년 4월 1일
댓글: Stephen23 2021년 4월 1일
I have a third-party function (one I can't edit) that takes an arbitrary-size array of input values, but then returns one argument for each input value (rather than returning an array of output values, which would seem to make a lot more sense). So I need to compile this set of variables of unknown length into a single cell array. Is there a clean way to do this? All I've come up with is to build a wrapper that looks at the input array size and then produces a string like '[Y{1},Y{2},Y{3}]=sillyFunction(X)' and then passes that to eval(), but generally when I have to resort to using eval() I'm doing something wrong.

채택된 답변

Steven Lord
Steven Lord 2021년 4월 1일
Use a comma-separated list. On that page there is an item in the "How to Use the Comma-Separated Lists" section that shows an example using them for collecting output arguments from a function.
numOut = 2;
C = cell(1, numOut);
x = randi([-10 10], 1, 10)
x = 1×10
2 5 2 -5 8 3 1 9 -8 -4
[C{:}] = max(x)
C = 1×2 cell array
{[9]} {[8]}
[value, location] = max(x)
value = 9
location = 8
The first cell in C filled in by the first max call contains the same information as the value output in the second call. Similarly the second cell of C matches the location output in the second call.
The only tricky thing is determining numOut, but from your description it sounds like you can compute that if you know the size or numel of the input that will be passed to the function you have to treat as a black box.
You can also use comma-separated lists for input.
Q = [C{:}] % concatenation
Q = 1×2
9 8
S = plus(C{:})
S = 17

추가 답변 (2개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 4월 1일
One of the easy and quick solution to your exercise is alike the following:
OUT = sillyFunction(X); % The output is a cell array
function Y=sillyFunction(X)
Y{1}= ...;
Y{2}=...;
Y{3}=...;
...
end
  댓글 수: 1
Lane
Lane 2021년 4월 1일
It seems like you are proposing a modification of sillyFunction to produce a cell array. Like I said in my original post, though, I can't modify sillyFunction. I have to work with it in its original form, where it produces one output argument for every input element. Am I misunderstanding you?

댓글을 달려면 로그인하십시오.


Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 4월 1일
If this is the case, then you'd need to convert the outputs into cell array after acquiring the outputs from the function - sillyFunction(X), e.g.:
for ii=1:numel(X)
OUT{ii}=sillyFunction(X(ii));
end

카테고리

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