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

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!

 採用された回答

Adam Danz
Adam Danz 2019 年 5 月 8 日
編集済み: Adam Danz 2019 年 5 月 8 日
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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeVariables についてさらに検索

質問済み:

2019 年 5 月 8 日

編集済み:

2019 年 5 月 8 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by