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.
MATLAB Answers: concatenate-or-merge-two-structures is very helpful and has several approches, including this, as adapted by me:
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
ssBadMerge = mergeFlatStructures(ssInto, ssFrom)
ssBadMerge: =
a: [1×1 struct]
b: '4' % kept. good.
ssBadMerge.a:
aa: [] % updated. good.
ac: 33 % added. 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.
引用格式
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. 检索时间: .
MATLAB 版本兼容性
创建方式
R2020a
兼容任何版本
平台兼容性
Windows macOS Linux标签
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!版本 | 已发布 | 发行说明 | |
---|---|---|---|
1.1.0 |