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

查看:18
本文介绍了通过 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.

推荐答案

既然您确信没有更简单的方法可以实现您想要的,这里是 Loren Shure 的文章(参见 Dan 评论中发布的链接),适用于您的示例:

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

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

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