How to concatenate structs with different fieldnames?

I'm looking for a way to concatenate structures which have different fieldnames into one struct array of with similar fieldnames.
Below you will find a minimum working example:
% Convert this
Object(1).Stats.Var1 = 1;
Object(1).Stats.Var2 = 2;
Object(2).Stats.Var1 = 1;
% Towards this
Output = [struct('Var1', 1, 'Var2', 2);
struct('Var1', 1, 'Var2', [])];
% But this doesn't work
[Object.Stats]
This returns an error message "Number of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of fields."

 Akzeptierte Antwort

Stephen23
Stephen23 am 12 Dez. 2018
Bearbeitet: Stephen23 am 12 Dez. 2018

0 Stimmen

Just use some loops (this will be quite efficient):
A(1).Stats.Var1 = 1;
A(1).Stats.Var2 = 2;
A(2).Stats.Var1 = 3;
Z = repmat(struct(),size(A));
for ii = 1:numel(A)
S = A(ii).Stats;
F = fieldnames(S);
for jj = 1:numel(F)
Z(ii).(F{jj}) = S.(F{jj});
end
end
And checking:
>> Z(1).Var1
ans = 1
>> Z(1).Var2
ans = 2
>> Z(2).Var1
ans = 3
>> Z(2).Var2
ans = []

1 Kommentar

JBl147
JBl147 am 18 Dez. 2018
Thanks!
Hoped for a one-liner, but this does the trick as well.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Matt J
Matt J am 11 Dez. 2018
Bearbeitet: Matt J am 11 Dez. 2018
[Object(1:2).Stats]=deal( struct('Var1', [], 'Var2', [])); %first, do this
Object(1).Stats.Var1 = 1;
Object(1).Stats.Var2 = 2;
Object(2).Stats.Var1 = 1;
Output=[Object.Stats]

1 Kommentar

JBl147
JBl147 am 12 Dez. 2018
Thanks, this works. Unfortunately, it does not fully solve my issue as I do not know the names of the variables and in which struct they are, so I can’t initialize using your first line.
Can you also solve it in this case?

Melden Sie sich an, um zu kommentieren.

Kategorien

Produkte

Version

R2015b

Gefragt:

am 11 Dez. 2018

Kommentiert:

am 18 Dez. 2018

Community Treasure Hunt

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

Start Hunting!

Translated by