Collect outputs from varargout

조회 수: 7 (최근 30일)
Matthew
Matthew 2012년 3월 6일
I am writing some code that utilizes heavy use of varargout. I am running into a problem with using functions that return variable arguments from within functions that return variable arguments. To illustrate this, I made a simple example.
function varargout = myfunc(varargin)
% myfunc
% Adds one and divides by two to each input argument
% Example usage:
% [A,B,C] = myfunc(1,2,3);
% Result:
% A = 1;
% B = 1.5;
% C = 2;
% Create output string for use in eval statement
% depending on number of inputs, makes something like this:
% [temp_var{1}, temp_var{2}, temp_var{3}]
output_str = '[';
for i = 1:length(varargin)
output_str = [output_str 'temp_var{' num2str(i) '}'];
if ~(i==length(varargin))
output_str = [output_str ', '];
end
end
output_str = [output_str ']'];
% Add one to each input then divide by 2
for i = 1:length(varargin)
eval([output_str ' = add_one(varargin{:});']);
varargout{i} = temp_var{i}/2;
end
end
function varargout = add_one(varargin)
% add_one
% Adds one to each input argument
% Example usage:
% [A,B,C] = add_one(1,2,3);
% Result:
% A = 2;
% B = 3;
% C = 4;
% Add one to each input
for i = 1:length(varargin)
varargout{i} = varargin{i} + 1;
end
end
I would like to be able to collect all of the outputs from the add_one function into a single cell array without using the eval statement with the appropriate number of output arguments as I did in the example above. Does anyone have a better way to do this without modifyinfg the add_one function?
  댓글 수: 2
Oleg Komarov
Oleg Komarov 2012년 3월 6일
Please avoid eval: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
Matthew
Matthew 2012년 3월 6일
Right. That's why I'm asking for a better way to do this.

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

답변 (1개)

Oleg Komarov
Oleg Komarov 2012년 3월 6일
I think you miss the point of varargout:
This does exctly the same, avoiding obscure eval construction:
function varargout = myfunc(varargin)
varargout = cellfun(@(x) (x+1)/2,varargin,'un',0);
end

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by