Matlab: Sum structures

2019-09-09 12:16发布

I'm looking for a very simple method to sum structures
which have identical substructure hierarchies.

Note: This began with an attempt to sum bus structures in Simulink.

MWE

Assume I have 2 structures red and blue.
Each structure has subfields a, b, and c.
Each subfield has subfields x1 and x2.

This is drawn below:

red. [a, b, c].[x1, x2]
blue.[a, b, c].[x1, x2]

Does a function exist such that a mathematical operator
may be applied to each parallel element of red and blue?

Something along the lines of:

purple = arrayfun( @(x,y) x+y, red, blue)

标签: matlab struct
1条回答
戒情不戒烟
2楼-- · 2019-09-09 12:20

Realizing that dynamic code which does support arbitrary structs and supports code generation is impossible (afaik), the best possibility to simplify coding is a function which generates the code:

function f=structm2(s)
    e=structm3(s);
    f=strcat('y.',e,'=plus(u.',e,',v.',e,');');
    f=sprintf('%s\n',f{:});
end

function e=structm3(s)
e={};
for f=fieldnames(s).'
    f=f{1};
    if isstruct(s.(f))
        e=[e,strcat([f,'.'],structm3(s.(f)))];
    else
        e{end+1}=f;
    end

end
end

You call structm2 inputting a struct and it returns the code:

y.a.x1=plus(u.a.x1,v.a.x1);
y.a.x2=plus(u.a.x2,v.a.x2);
y.b.x1=plus(u.b.x1,v.b.x1);
y.b.x2=plus(u.b.x2,v.b.x2);
查看更多
登录 后发表回答