如何在 Matlab 中 return 结构的叶子作为向量?

How to return the leaves of a struct as vector in Matlab?

我经常需要访问结构化数组中数据的叶子进行计算。 如何在 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, and every entry below is a scalar structure, you can collect the leaves with a call to 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] 失败的原因是因为点索引 returns comma-separated list apple.properties 的结构。您需要将此列表收集到一个新的结构数组中,然后将点索引应用于下一个字段 weight.

你可以收集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)