Convert a cell containing structs into a single Struct

10 Ansichten (letzte 30 Tage)
ROYGBIV
ROYGBIV am 7 Feb. 2025
Kommentiert: ROYGBIV am 7 Feb. 2025
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,[]}
mycell = 1x4 cell array
{0x0 double} {1x1 struct} {1x1 struct} {0x0 double}
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)
ans = logical
1

Akzeptierte Antwort

Stephen23
Stephen23 am 7 Feb. 2025
Bearbeitet: Stephen23 am 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,[]}
mycell = 1x4 cell array {0x0 double} {1x1 struct} {1x1 struct} {0x0 double}
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
out = 4x1 struct array with fields:
a b c
Checking:
out.a
ans = []
ans = 1
ans = 10
ans = []
out.b
ans = []
ans = 2
ans = 20
ans = []
out.c
ans = []
ans = 3
ans = 30
ans = []

Weitere Antworten (0)

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by