Convert a cell containing structs into a single Struct
8 views (last 30 days)
Show older comments
I am looking for a less convoluted way of changing a cell array that contains structs and empty arrys in a random order, into a sinlge struct.
I have a cell that contains the structs with similar fileds and empty cell elements in any random order as follows:
s1 = struct('a',1, 'b',2, 'c',3);
s2 = struct('a',10,'b',20,'c',30);
mycell = {[],s1,s2,[]}
I want to convert this cell into a struct that would look like this:
s = struct('a',{}, 'b',{}, 'c',{});
s(2) = s1;
s(3) = s2;
s(4) = struct('a',[], 'b',[], 'c',[]);
the way I am thinking of doing this is:
% first check which cell element conntaians a struct
for ii = 1:length(mycell)
if isa(mycell{ii},'struct')
fname = fieldnames(mycell{ii});
break
end
end
aa= sprintf('''%s'',{},',fname{:});
aa(end) = '';
S = eval(strcat('struct(',aa,')'));
for ii = 1:length(mycell)
if isa(mycell{ii},'struct')
S(ii) = mycell{ii};
else
aa= sprintf('''%s'',[],',fname{:});
aa(end) = '';
S(ii) = eval(strcat('struct(',aa,')'));
end
end
isequal(S, s)
0 Comments
Accepted Answer
Stephen23
on 7 Feb 2025
Edited: Stephen23
on 7 Feb 2025
Avoid evil EVAL(). Constructing text that looks like code and then evaluating it should definitely be avoided.
Using comma-separated lists would be much much better:
Using your fake data:
s1 = struct('a',1, 'b',2, 'c',3);
s2 = struct('a',10,'b',20,'c',30);
mycell = {[],s1,s2,[]}
Here is a much better approach based on CELL2STRUCT():
idx = ~cellfun('isempty',mycell);
tmp = [mycell{idx}]; % ensures identical fieldnames
fnm = fieldnames(tmp);
out = cell2struct(cell(numel(mycell),numel(fnm)),fnm,2);
out(idx) = tmp
Checking:
out.a
out.b
out.c
More Answers (0)
See Also
Categories
Find more on Cell Arrays 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!