Matlab: how to sum fields of two equivalent structures?
I am working in Matlab. I have defined:
a(1).x=1; a(1).y=2; a(1).z.w=3; a(2).x=4; a(2).y=5; a(2).z.w=6;
Now I am trying to add fields to two structures a (1) and a (2) such that I get:
c.x = 5;
c.y = 7;
c.z.w = 9;
Any idea how I can do this in an elegant way? Note that in the original problem, the structures have many more fields (about 50).
Thank you in advance! Jose
+3
source to share
3 answers
Here is a solution for any depth of structure
Script command code (or MATLAB)
a(1).x=1;
a(1).y=2;
a(1).z.w=3;
a(2).x=4;
a(2).y=5;
a(2).z.w=6;
c=a(1);
c = returnStruct(c, a(2));
%{
you can also sum any amount of structs
for i=2:length(a)
c=returnStruct(c, a(i));
end
%}
with recursive function
function rs = returnStruct(s,a)
fn = fieldnames(s);
for i=1:length(fn)
if isstruct(s.(fn{i}))
s.(fn{i}) = returnStruct(s.(fn{i}), a.(fn{i}));
else
s.(fn{i}) = s.(fn{i})+a.(fn{i});
end
end
rs = s;
end
I tested it for deeper levels of structures and it worked great. Maybe you need to adjust it a little to your case, but this should be the way to go.
Unfortunately, any type function struct2cell
only converts the first level, so you need something else.
+5
source to share
If the deepest level of the substructure is 2, then this code will work:
fields=fieldnames(a);
for i=1:numel(fields)
if isstruct(a(1).(fields{i}))
fields2=fieldnames(a(1).(fields{i}));
for j=1:numel(fields2)
a(3).(fields{i}).(fields2{j})= a(1).(fields{i}).(fields2{j})+a(2).(fields{i}).(fields2{j});
end
else
a(3).(fields{i})=a(1).(fields{i})+a(2).(fields{i});
end
end
0
source to share