MATLAB: How to set missing fields in a structure array to default values stored in another structure array (with same field names)

MATLABMATLAB Compilermerge fieldsstructures

Hi Everyone,
I am wondering if there is a way to set 'missing' fields in a structure to 'default' values stored in a default structure. For example, say I have the structures 's' and 'd' below, and want to set any fields that 'd' contains that to not exist in 's' to the values in 'd'.
s.fa = 1;
s.fb = 'b';
d.fa = 1;
d.fb = 'a';
d.fc = "a";
I would like to create the field s.fc = d.fc, without changing the value of s.fb to d.fb.
For some background, I am developing a Matlab application in App Developer, and I am storing 'designs' as structures and structure arrays in .mat files. I am frequently expanding capabilities and fields, and would like to maintain backwards compatibility for previous designs (which have less fields), by setting missing fields to default values stored in a default structure. The actual design will contain nested structures (structure levels?), as well as structure arrays that are not necessarily the same size.
Thanks!

Best Answer

This solution lists the field names in each structure, determines which ones are missing in 's', and then uses dynamic field names to assign the values from d to s for those fields that are missing.
% Your example data
s.fa = 1;
s.fb = 'b';
d.fa = 1;
d.fb = 'a';
d.fc = "a";
% List fields in both structs
sf = fieldnames(s);
df = fieldnames(d);
% List fields missing in s
missingIdx = find(~ismember(df,sf));
% Assign missing fields to s
for i = 1:length(missingIdx)
s.(df{missingIdx(i)}) = d.(df{missingIdx(i)});
end