How to save an indefinite number of outputs to a struct
Show older comments
I have a function that depending on the number of inputs I give it, it will give the same number of outputs. I want a way that I can save these outputs, regardless of how many there are, to a struct. This is what I have so far
varnames = cell(1,num_params); % Set a cell array with number of input as the length
varnames(:) = {'A'}; % Make each input 'A'
varnames = genvarname(varnames,'A'); % make each entry A1,A2,A3,...
Here num_params is the natural number of parameters I pass to it. I tried to add the lines
dis_obj.(varnames) = myfunc(paramlist{:});
AND
dis_obj.(varnames(:)) = myfunc(paramlist{:});
AND
dis_obj.(varnames{:}) = myfunc(paramlist{:});
but all of these games me errors. The goal here is to have my outputs be assigned to A1, A2, A3, ... where there are num_params outputs. Is there anyway to do this?
Accepted Answer
More Answers (1)
num_params = 3;
varnames = "A" + (1:num_params)' % String arrays are neat...
% Make up some output...
out1 = table(rand(2,1),rand(2,1),'VariableNames',{'a','b'});
out2 = "a_string";
out3 = magic(3);
% Make a cell array (or a normal array if that's what your function does)
vals = {out1;out2;out3};
dis_obj = containers.Map(varnames, vals)
keys(dis_obj) % Get the names
values(dis_obj) % and their values.
dis_obj('A1') % Retrieve a value by varname
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!