如何从 Matlab 中的 n*1 结构的特定字段中提取所有值

How to extract all the values from a specific field of a n*1 structure in Matlab

假设我有一个名为 I 的结构,大小为 n*1,有多个字段,例如,其中一个字段称为 'area'。当我尝试下面的代码时:

area = I.area

结果区域只有一个值来自结构的最后一个位置。除了使用 for 循环外,是否有任何快速的方法来精确计算字段中的所有值:

for ii = 1:n; area(ii) = I(ii).area; end
area = [I.area]

I.area returns I(1).area, I(2).area 的所有值 ... 作为逗号分隔的列表,可以将其插入任何需要此类列表的地方,例如函数参数列表或数组初始化。

编辑:如果所有 I(i).area 都是大小相等的行向量。然后你可以先水平连接所有这些,然后重塑到所需的尺寸:

area =  reshape([I.area], [2 length(I)])'

结果:

>> I.area

ans =

     3     4


ans =

     5     6


ans =

     7     8

>> reshape([I.area], [2 length(I)])'

ans =

     3     4
     5     6
     7     8

在结构周围使用简单的 [] 将导致所有值的水平串联。如果您想沿另一个维度连接它们,则可以使用 cat 明确指定。这将使您能够更好地处理可能包含多个值的字段。

% Concatenate them along the first dimension
out = cat(1, I.area);

% Concatenate them along the third dimension
out = cat(2, I.area);

或者,如果字段都是 不同的 维度,则将它们变成 cell

out = {I.area};