Jirka cigler
Jirka cigler

Reputation: 405

Recursive concatenation of Matlab structs

Is it somehow possible to concatenate two matlab structures recursively without iterating over all leaves of one of the structures.

For instance

x.a=1;

x.b.c=2;

y.b.d=3;

y.a = 4 ;

would result in the following

res = mergeStructs(x,y)

res.a=4

res.b.c=2

res.b.d=3

Upvotes: 4

Views: 1221

Answers (1)

Ramashalanka
Ramashalanka

Reputation: 8854

The following function works for your particular example. There will be things it doesn't consider, so let me know if there are other cases you want it to work for 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 you require.

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 big struct and ~isstruct(x).

Upvotes: 6

Related Questions