Arrays 如何在Matlab中以向量形式返回结构的叶子?

Arrays 如何在Matlab中以向量形式返回结构的叶子?,arrays,matlab,struct,object-slicing,Arrays,Matlab,Struct,Object Slicing,我经常需要访问结构化数组中的数据叶子进行计算。 如何在Matlab2017b中最好地实现这一点 %最小工作示例: 蛋(1),重量=30; 蛋(2),重量=33; 蛋(3),体重=34; SomeOggs=平均值([egg.weight])%可以正常工作 苹果(1).properties.weight=300; 苹果(2).properties.weight=330; 苹果(3).properties.weight=340; SomeApple=平均值([apple.properties.weig

我经常需要访问结构化数组中的数据叶子进行计算。 如何在Matlab2017b中最好地实现这一点

%最小工作示例:
蛋(1),重量=30;
蛋(2),重量=33;
蛋(3),体重=34;
SomeOggs=平均值([egg.weight])%可以正常工作
苹果(1).properties.weight=300;
苹果(2).properties.weight=330;
苹果(3).properties.weight=340;
SomeApple=平均值([apple.properties.weight])%失败
权重=[apple.properties.weight]%也失败
%应为大括号或点索引表达式的一个输出,
%但有3个结果。

如果只有顶层是非标量的,而下面的每个条目都是标量结构,则可以通过调用来收集叶子,然后对返回的向量进行计算:

>> 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]
失败的原因是点索引为
apple.properties
返回一系列结构。您需要将此列表收集到一个新的结构数组中,然后对下一个字段的
权重

应用点索引。您可以将
属性
收集到一个临时结构数组中,然后正常使用它:

apple_properties = [apple.properties];
someapples = mean([apple_properties.weight]) %works
如果有更多的嵌套级别,这将不起作用。也许是这样的:

apple(1).properties.imperial.weight = 10;
apple(2).properties.imperial.weight = 15;
apple(3).properties.imperial.weight = 18;
apple(1).properties.metric.weight = 4;
apple(2).properties.metric.weight = 7;
apple(3).properties.metric.weight = 8;
并不是说我会建议这样的结构,但它可以作为一个玩具的例子。在这种情况下,您可以在两个步骤中执行与前面相同的操作。。。或者您可以使用
arrayfun

weights = arrayfun(@(x) x.properties.metric.weight, apple);
mean(weights)

你想要这个仅仅是为了你的例子,还是为了任何任意的结构?@gnovice对于
a(k).b.c….z
类型的任何结构,我想要
z(k)
我已经添加了一个注释,这是一个例子。但是,如果我需要在解决方案中进行一些更改,以便将其应用到结构中,这是很好的。