arrays - 如何在 Matlab 中将结构体的叶子作为向量返回?

标签 arrays matlab struct object-slicing

我经常需要访问结构化数组中的数据叶子进行计算。 在 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/

相关文章:

java - 在一个包含 27 个字符串的数组中创建一个包含 9 个唯一字符串的新数组

arrays - 找出两个排序数组的最大总和

arrays - 在 Fortran 中更改分配数组的形状

python - interp2(X, Y, Z, XI, YI) 从 Matlab 到 Python

matlab - 为什么按 F9 时 matlab 执行时间不同

c - 结构中大小的读取无效

go - 如何使用接口(interface)来规范化不同的结构?

arrays - 为 OSX 创建并定义 NSButton 数组

c++ - 将 Matlab eig(A,B)(广义特征值/特征向量)重写为 C/C++

arrays - vb.net独特的结构数组