"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)
validateattributes(from, {'struct'}, {'scalar'});
validateattributes(into, {'struct'}, {'scalar'});
fns = fieldnames(from);
for fn = fns.'
if isstruct(from.(fn{1})) && isfield(into, fn{1})
into.(fn{1}) = mergestruct(into.(fn{1}), from.(fn{1}));
else
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.
Best Answer