Convert a cell containing structs into a single Struct
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2025-2-7
编辑:Stephen23
2025-2-7
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!