Convert a cell containing structs into a single Struct
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)
Accepted Answer
More Answers (0)
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!