我想知道是否有一种方便的方法来更新结构与Matlab中的另一个结构的值.下面是代码,与使用fieldnames,numel以及for循环,
fn = fieldnames(new_values);
for fi=1:numel(fn)
old_struct.(fn{fi}) = new_values.(fn{fi});
end
Run Code Online (Sandbox Code Playgroud)
当然,我不希望失去在田野old_struct中没有的new_values,所以我不能用简单old_struct=new_values.
更新结构是我们可能想要在解释器中的单个短行中执行的操作.
既然你确信没有更简单的方法来实现你想要的东西,那么Loren Shure的文章(参见Dan的评论中的链接)中描述的方法适用于你的例子:
%// 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);
Run Code Online (Sandbox Code Playgroud)
请注意,这个稍微改进的版本可以处理结构数组,以及具有重叠字段名称的结构(这就是我认为你称之为碰撞).