我经常需要访问结构化数组中的数据叶子进行计算。 在 Matlab 2017b 中如何最好地完成此操作?
% Minimal working example:
egg(1).weight = 30;
egg(2).weight = 33;
egg(3).weight = 34;
someeggs = mean([egg.weight]) % works fine
apple(1).properties.weight = 300;
apple(2).properties.weight = 330;
apple(3).properties.weight = 340;
someapples = mean([apple.properties.weight]) %fails
weights = [apple.properties.weight] %fails too
% Expected one output from a curly brace or dot indexing expression,
% but there were 3 results.
最佳答案
如果只有顶层是非标量 structure array ,并且下面的每个条目都是标量结构,您可以通过调用 arrayfun
来收集叶子。 ,然后对返回的向量进行计算:
>> weights = arrayfun(@(s) s.properties.weight, apple) % To get the vector
weights =
300 330 340
>> someapples = mean(arrayfun(@(s) s.properties.weight, apple))
someapples =
323.3333
[apple.properties.weight]
失败的原因是点索引返回 comma-separated list apple.properties
的结构。您需要将此列表收集到一个新的结构数组中,然后对下一个字段weight
应用点索引。
关于arrays - 如何在 Matlab 中将结构体的叶子作为向量返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47021480/