finds any fields in struct2 that are not in struct1 and copies them to struct1 The values of the fields that both structs have in common will not be overwritten in struct1. The fields missing from struct1 will be populated with the values in struct2. This function is useful for populating a parameter structure with default values which may be missing from the specified parameters. Copyright (c) 2008-2012 The Regents of the University of California All Rights Reserved. Authors: 10/9/2008 - Stefan Tomic, first version.
0001 function struct1 = struct_union(struct1,struct2) 0002 % 0003 % finds any fields in struct2 that are not in struct1 and copies them to struct1 0004 % 0005 % The values of the fields that both structs have in common will not be overwritten 0006 % in struct1. The fields missing from struct1 will be populated 0007 % with the values in struct2. This function is useful for 0008 % populating a parameter structure with default values which may be 0009 % missing from the specified parameters. 0010 % 0011 % Copyright (c) 2008-2012 The Regents of the University of California 0012 % All Rights Reserved. 0013 % 0014 % Authors: 0015 % 10/9/2008 - Stefan Tomic, first version. 0016 % 0017 0018 0019 fnamesStruct1 = fieldnames(struct1); 0020 fnamesStruct2 = fieldnames(struct2); 0021 0022 nFields = length(fnamesStruct2); 0023 for iField = 1:nFields 0024 thisField = fnamesStruct2{iField}; 0025 if(~isfield(struct1,thisField)) 0026 struct1.(thisField) = struct2.(thisField); 0027 elseif(strcmp(class(struct1.(thisField)),'struct') && ... 0028 strcmp(class(struct2.(thisField)),'struct')) 0029 %if corresponding fields in both structs are themselves structs 0030 %(substructs), then we'll perform a struct_union on them. If 0031 %one of them is not a struct (this should be unlikely), then 0032 %we'll bypass this altogether 0033 struct1.(thisField) = struct_union(struct1.(thisField),struct2.(thisField)); 0034 end 0035 end