问题
I'm wondering if there is a convenient way to update a struct with the values of another struct in Matlab.
Here is the code, with the use of fieldnames, numel and a for loop,
fn = fieldnames(new_values);
for fi=1:numel(fn)
old_struct.(fn{fi}) = new_values.(fn{fi});
end
Of course, I don't want to loose the fields in old_struct that are not in new_values, so I can't use the simple old_struct=new_values.
Updating a struct is something we may want to do in a single short line in an interpreter.
回答1:
Since you are convinced that there is no simpler way to achieve what you want, here is the method described in Loren Shure's article (see link posted in Dan's comment), applied to your example:
%// Remove overlapping fields from first struct
s_merged = rmfield(s_old, intersect(fieldnames(s_old), fieldnames(s_new)));
%// Obtain all unique names of remaining fields
names = [fieldnames(s_merged); fieldnames(s_new)];
%// Merge both structs
s_merged = cell2struct([struct2cell(s_merged); struct2cell(s_new)], names, 1);
Note that this slightly improved version can handle arrays of structs, as well as structs with overlapping field names (this is what I believe you call collision).
来源:https://stackoverflow.com/questions/15245167/update-struct-via-another-struct-in-matlab