Convert a cell containing structs into a single Struct

8 vues (au cours des 30 derniers jours)
ROYGBIV
ROYGBIV le 7 Fév 2025
Commenté : ROYGBIV le 7 Fév 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

Réponse acceptée

Stephen23
Stephen23 le 7 Fév 2025
Modifié(e) : Stephen23 le 7 Fév 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 = []

Plus de réponses (0)

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by