Matlab:如何求和两个等价结构的字段?

时间:2015-06-02 08:51:40

标签: matlab data-structures

我在Matlab工作。我已定义:

a(1).x=1;
a(1).y=2;
a(1).z.w=3;

a(2).x=4;
a(2).y=5;
a(2).z.w=6;

我现在正试图在两个结构a(1)和a(2)中添加字段,以便得到:

c.x = 5; 
c.y = 7; 
c.z.w = 9; 

知道如何以优雅的方式做到这一点吗?请注意,在原始问题中,结构有更多字段(大约50个)。

非常感谢您提前! 何

3 个答案:

答案 0 :(得分:5)

对于任何深度的结构

,这是一个解决方案

脚本代码(或MATLAB命令)

request:("/path1" OR "/path2" OR "/path3")

使用递归函数

a(1).x=1;
a(1).y=2;
a(1).z.w=3;

a(2).x=4;
a(2).y=5;
a(2).z.w=6;
c=a(1);
c = returnStruct(c, a(2));
%{
you can also sum any amount of structs
for i=2:length(a)
   c=returnStruct(c, a(i));
end
%}

我测试了更深层次的结构,它运作得很好。也许,你必须稍微适应你的情况,但这应该是要走的路。

不幸的是,像function rs = returnStruct(s,a) fn = fieldnames(s); for i=1:length(fn) if isstruct(s.(fn{i})) s.(fn{i}) = returnStruct(s.(fn{i}), a.(fn{i})); else s.(fn{i}) = s.(fn{i})+a.(fn{i}); end end rs = s; end 这样的任何函数只会转换第一级,所以你需要别的东西。

答案 1 :(得分:0)

如果最深的子结构级别为2,则此代码将起作用:

fields=fieldnames(a);
for i=1:numel(fields)
if isstruct(a(1).(fields{i}))
fields2=fieldnames(a(1).(fields{i}));
for j=1:numel(fields2)
a(3).(fields{i}).(fields2{j})= a(1).(fields{i}).(fields2{j})+a(2).(fields{i}).(fields2{j});
end
else
a(3).(fields{i})=a(1).(fields{i})+a(2).(fields{i});
end
end

答案 2 :(得分:0)

您可以使用简单的递归解决方案

function r = sumfields(s)
if isstruct(s)
    for f = fieldnames(s).'
        r.(f{1}) = sumfields([s.(f{1})]);
    end
else
    r = sum(s);
end
end