我如何总结不同的领域?我想总结材料(1)的所有信息......所以我想添加 5+4+6+300 但我不确定如何。除了做材料(1)之外还有另一种方法。五月+材料(1)。六月等....
material(1).May= 5;
material(1).June=4;
material(1).July=6;
material(1).price=300;
material(2).May=10;
material(2).price=550;
material(3).May=90;
您可以structfun
为此使用:
result = sum( structfun(@(x)x, material(1)) );
内部部分 ( structfun(@(x)x, material(1))
) 对结构中的每个单独字段运行一个函数,并以数组的形式返回结果。通过使用恒等函数 ( @(x)x
),我们只需获取值。 sum
当然做显而易见的事情。
一个稍长的方法是在循环中访问每个字段。例如:
fNames = fieldnames(material(1));
accumulatedValue = 0;
for ix = 1:length(fNames)
accumulatedValue = accumulatedValue + material(1).(fNames{ix});
end
result = accumulatedValue
对于一些用户来说,这将更容易阅读,尽管对于专家用户来说,第一个会更容易阅读。结果和(近似)性能是相同的。
我认为 Pursuit 的答案非常好,但这是我脑海中的另一种选择:
sum( cell2mat( struct2cell( material(1) )));