在MATLAB中结合两种结构的有效方法有哪些? [英] What are some efficient ways to combine two structures in MATLAB?

查看:78
本文介绍了在MATLAB中结合两种结构的有效方法有哪些?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想结合两个具有不同字段名称的结构.

I want to combine two structures with differing fields names.

例如,从以下开始:

A.field1 = 1;
A.field2 = 'a';

B.field3 = 2;
B.field4 = 'b';

我想拥有:

C.field1 = 1;
C.field2 = 'a';
C.field3 = 2;
C.field4 = 'b';

有没有比使用字段名"和for循环更有效的方法?

Is there a more efficient way than using "fieldnames" and a for loop?

编辑:假设在字段名称冲突的情况下,我们优先选择A.

Let's assume that in the case of field name conflicts we give preference to A.

推荐答案

没有冲突,您可以做到

M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
C=struct(M{:});

这是相当有效的.但是,重复字段名上的struct错误,并使用unique进行预先检查会导致性能下降,从而使循环更好.但这是它的样子:

And this is reasonably efficient. However, struct errors on duplicate fieldnames, and pre-checking for them using unique kills performance to the point that a loop is better. But here's what it would look like:

M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];

[tmp, rows] = unique(M(1,:), 'last');
M=M(:, rows);

C=struct(M{:});

您可以通过假设没有冲突,并在对struct的调用周围使用try/catch来优雅地降级到冲突处理情况,从而做出混合解决方案.

You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to struct to gracefully degrade to the conflict handling case.

这篇关于在MATLAB中结合两种结构的有效方法有哪些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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