The following function works for your specific example. There will be things that he does not take into account, so let me know if there are other cases that you want to work on, and I can update.
function res = mergeStructs(x,y) if isstruct(x) && isstruct(y) res = x; names = fieldnames(y); for fnum = 1:numel(names) if isfield(x,names{fnum}) res.(names{fnum}) = mergeStructs(x.(names{fnum}),y.(names{fnum})); else res.(names{fnum}) = y.(names{fnum}); end end else res = y; end
Then res = mergeStructs(x,y); gives:
>> res.a ans = 4 >> res.b ans = c: 2 d: 3
as needed.
EDIT: I added isstruct(x) && to the first line. The old version worked fine because isfield(x,n) returns 0 if ~isstruct(x) , but the new version is slightly faster if y is a large structure and ~isstruct(x) .
source share