MATLAB: Partial overwrite of data in a structure

merge structuresmergingstructures

Is it possible to partially overwrite a structure? Let say I have two structures:
a.a=1;a.b=2;a.c=3;
and
b.a=11; b.b=12;
if I write a=b
, then I will have two exactly the same "b" structures. Instead I would like to end up with
a.a=11;a.b=12; a.c=3;
structure. So if there is such a member in the second structure it should be overwritten in the first, if there is no such a member in the second structure it should be untouched in the first. And it should work in the nested structures as well.
So is there any command or a short and fast solution? I am in a development of an evaluation of measurements, and when I am restructuring the data it always a hassle to put every data holder variable to a proper place. Once I am ready there will be no problem.
Thanks if you answer.
Csaba

Best Answer

"when I am restructuring the data it always a hassle to put every data holder variable to a proper place" If it's a hassle, then your storage structure is not optimal. You may be better off revising the way you store your data rather than constantly finding workarounds.
To answer your question, this should do what you want:
function into = mergestruct(into, from)
%MERGESTRUCT merge all the fields of scalar structure from into scalar structure into
validateattributes(from, {'struct'}, {'scalar'});
validateattributes(into, {'struct'}, {'scalar'});
fns = fieldnames(from);
for fn = fns.'
if isstruct(from.(fn{1})) && isfield(into, fn{1})
%nested structure where the field already exist, merge again
into.(fn{1}) = mergestruct(into.(fn{1}), from.(fn{1}));
else
%non structure field, or nested structure field that does not already exist, simply copy
into.(fn{1}) = from.(fn{1});
end
end
end
Test:
>> a = struct('a', 1, 'b', 2, 'c', 3, 'd', struct('a', 11, 'b', 12, 'c', struct('a', 111)))
a =
struct with fields:
a: 1
b: 2
c: 3
d: [1×1 struct]
>> a.d
ans =
struct with fields:
a: 11
b: 12
c: [1×1 struct]
>> a.d.c
ans =
struct with fields:
a: 111
>> b = struct('a', -1, 'b', -2, 'd', struct('b', -12, 'c', struct('b', -112)))
b =
struct with fields:
a: -1
b: -2
d: [1×1 struct]
>> aa = mergestruct(a, b)
aa =
struct with fields:
a: -1
b: -2
c: 3
d: [1×1 struct]
>> aa.d
ans =
struct with fields:
a: 11
b: -12
c: [1×1 struct]
>> aa.d.c
ans =
struct with fields:
a: 111
b: -112
Seems to do what you want.