Matlab:求和结构 [英] Matlab: Sum structures
问题描述
我正在寻找一种求和结构的简单方法
具有相同的子结构层次结构.
I'm looking for a very simple method to sum structures
which have identical substructure hierarchies.
注意:这始于尝试假设我有2个结构red
和blue
.
每个结构都有子字段a
,b
和c
.
每个子字段都有子字段x1
和x2
.
Assume I have 2 structures red
and blue
.
Each structure has subfields a
, b
, and c
.
Each subfield has subfields x1
and x2
.
这画在下面:
red. [a, b, c].[x1, x2]
blue.[a, b, c].[x1, x2]
是否存在这样的函数,使得数学运算符
可以应用于red
和blue
的每个并行元素吗?
Does a function exist such that a mathematical operator
may be applied to each parallel element of red
and blue
?
类似的东西:
purple = arrayfun( @(x,y) x+y, red, blue)
推荐答案
意识到实现支持任意结构并支持代码生成的动态代码是不可能的(afaik),简化编码的最佳可能性是生成代码的函数:
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
您调用structm2
输入一个结构,它返回代码:
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);
这篇关于Matlab:求和结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!