Matlab: Sum structures

别来无恙 提交于 2020-01-07 04:35:21

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/35853450/matlab-sum-structures

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!