Recursive concatenation of Matlab structures

Is it possible in any way to concatenate two matrix structures recursively without repeating all sheets of one of the structures.

for instance

xa = 1;

xbc = 2;

ybd = 3;

ya = 4;

will lead to the following

res = mergeStructs (x, y)

res.a = 4

res.bc = 2

res.bd = 3

+4
source share
1 answer

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) .

+6
source

All Articles