在 MATLAB 中组合两个结构体的有效方法有哪些? [英] What are some efficient ways to combine two structures in 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屋!