How to redirect function output arguments to a cell array
이전 댓글 표시
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.
댓글 수: 1
"...generally when I have to resort to using eval() I'm doing something wrong."
Yes.
채택된 답변
추가 답변 (3개)
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
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
Based on previous answers, I created a simple generic function that captures the n-th output from any function func.
So I'm just putting it here since it could be useful for someone else:
function o = get_n_output(n,func,varargin)
% n -> position of the output to capture
% func -> function to call
% varargin -> ordered arguments for function func
%
% returns:
% n-th output of func(varargin{:})
output = cell(1,n);
[output{:}] = func(varargin{:});
o = output{n};
end
For example, if you have a function
function [a,b,c] = do_something(arg1,arg2,arg3)
% do something, e.g.
a = arg1;
b = arg2;
c = arg3;
end
And you want to get only the 2nd output, you can call
b = get_n_output(2,@do_something,1,2,3); % returns b=2
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!