通过Matlab中的另一个结构更新结构 [英] update struct via another struct in Matlab

查看:89
本文介绍了通过Matlab中的另一个结构更新结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种便捷的方法来用Matlab中的另一个结构的值更新结构. 这是使用fieldnamesnumelfor循环的代码,

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

当然,我不想丢失old_struct中不在new_values中的字段,因此我不能使用简单的old_struct=new_values.

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.

推荐答案

由于您确信没有简单的方法可以实现所需的功能,因此以下是

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);

请注意,此稍作改进的版本可以处理结构数组以及具有重叠字段名称的结构(这就是我所说的 collision ).

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).

这篇关于通过Matlab中的另一个结构更新结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆