How to save an indefinite number of outputs to a struct
조회 수: 3 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Stephen23
2022년 11월 7일
편집: Stephen23
2022년 11월 7일
"Is there anyway to do this?"
Of course. But forcing pseudo-indices into structure fieldnames is much less efficient and more complex than simply using actual indices of a non-scalar structure. Using another cell array rather than a structure is probably the simplest and most efficient approach: a good rule of thumb is to keep data design as simple as reasonably possible.
Here I call NDGRID to demonstrate how it works, but of course you will call your own function:
A = {1:3,4:6,7:9} % example input cell array
C = A; % preallocate output cell array
[C{:}] = ndgrid(A{:}) % call function
Ah, very simple and very efficient code due to simpler data design.
Now with a structure array, also a reasonable approach:
S = struct('data',A); % preallocate structure array
[S.data] = ndgrid(A{:}) % call function
If you really want to follow your complex approach of hiding pseudo-indices in fieldnames, then CELL2STRUCT is one way (note how this just adds more complexity on top of simply using the cell array. You cannot avoid this because there is no comma-separated list syntax which allocates to different fields).
F = "A" + (1:numel(A));
inefficientDataDesign = cell2struct(C,F,2)
Read more:
댓글 수: 0
추가 답변 (1개)
Chris
2022년 11월 7일
편집: Chris
2022년 11월 7일
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!