update struct via another struct in Matlab [duplicate]

若如初见. 提交于 2019-12-28 15:35:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!