mergeStructures(): merge or concatenate nested structures

Version 1.1.0 (4.18 KB) by
merge nested structures, recursively
Updated 28 Jun 2023

function ssMerged = mergeStructures(ssDest, ssSource)
Add or copy fields from nested structure ssSource into ssDest
My data acquisition code uses a large nested structure to hold the settings and parameters used in the acquisition. Fields include the settings for the various instruments, experimental conditons and the like. The problem is how to update (or add) various fields and branches in the structure while retaining all the other values unchanged. With this ability I can write small .json or .mat files with updated parameters and easily merge these with the current settings.
function ssMerge = mergeFlatStructures( ssInto, ssFrom)
ssMerge = ssInto;
ff = fieldnames( ssFrom );
for i = 1:numel(ff)
ssInto.(ff{i}) = ssFrom.(ff{i});
end
end
which works perfectly for flat structures.
But if we do:
clear( 'ssInto' )
ssInto.a.aa = 1; % to update
ssInto.a.ab = 2; % to keep
ssInto.b = '4'; % to keep
clear( 'ssFrom' )
ssFrom.a.aa = []; % new value
ssFrom.a.ac = 33; % new field
a: [1×1 struct]
b: '4' % kept. good.
aa: [] % updated. good.
% Problem! a.ab has gone!
we see that field a.ab has been lost.
The solution is to recurse when the field in the source is a structure, as per the submission.
>> ssGoodMerge = mergeStructures(ssInto, ssFrom);
>> fprintf( 'ssGoodMerge:\n'); disp( ssGoodMerge )
ssGoodMerge:
a: [1×1 struct]
b: '4'
>> fprintf( 'ssGoodMerge.a:\n'); disp( ssGoodMerge.a )
ssGoodMerge.a:
aa: [] % note empty field copied
ab: 2
ac: 33
we see that ssGoodMerge.a.ab has been kept. Which is the whole point of the submission.
Arrays of structures:
• ssInto and ssFrom may be struct arrays of the same size.
• Each (scalar) element of the source array is merged with its corresponding element in the destination.
Empty fields:
• Empty fields in a scalar (size 1-by-1) source overwrite destination.
• Empty fields in an array source DO NOT overwrite destination; this makes it easier to update just a few elements of an array.
Demo code:
mergeStructuresDemo()
shows
• mergeFlatStructures() failing with a simple nested struct.
• mergeStructures() with simple inputs
• mergeStructures() with struct array inputs
• mergeStructures() with file reading, nested struct array inputs and null handling
Thanks to user Stephen23 for his helpful comments on an earlier version of this submission.

Cite As

RST (2024). mergeStructures(): merge or concatenate nested structures (https://www.mathworks.com/matlabcentral/fileexchange/131718-mergestructures-merge-or-concatenate-nested-structures), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2020a
Compatible with any release
Platform Compatibility
Windows macOS Linux