如何对不同字段求和?我想对材料(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;
Run Code Online (Sandbox Code Playgroud)
您可以structfun为此使用:
result = sum( structfun(@(x)x, material(1)) );
Run Code Online (Sandbox Code Playgroud)
内部部分 ( 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
Run Code Online (Sandbox Code Playgroud)
对于某些用户来说,这将更容易阅读,但对于专家用户来说,第一个将更容易阅读。结果和(近似)性能是相同的。