Collect outputs from varargout
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Oleg Komarov
le 6 Mar 2012
Please avoid eval: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
Réponses (1)
Oleg Komarov
le 6 Mar 2012
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
0 commentaires
Voir également
Catégories
En savoir plus sur Scope Variables and Generate Names dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!