MATLAB:从结构数组中收集

sec*_*ond 2 arrays matlab matlab-struct

例如,输出>>w = whos;返回结构数组.我想构造一个数组,其元素是每个结构中特定字段名称的标量.

这样做最明显的方法并不是按照我的意愿返回数组,而是分别回答每个数组.

>> w(1:2).bytes
ans =
    64
ans =
   128
Run Code Online (Sandbox Code Playgroud)

我可以用循环来做,但是想知道是否有更好的方法.

Mr *_*ooz 10

在表达式周围放置方括号,即

[w(1:2).bytes]
Run Code Online (Sandbox Code Playgroud)


gno*_*ice 6

访问结构数组的字段将作为输出返回逗号分隔列表(或CSL).换句话说,您的示例的输出:

w(1:2).bytes
Run Code Online (Sandbox Code Playgroud)

输入相当于:

64, 128
Run Code Online (Sandbox Code Playgroud)

因此,您可以在可以使用CSL的任何位置使用输出.这里有些例子:

a = [w(1:2).bytes];         % Horizontal concatenation = [64, 128]
a = horzcat(w(1:2).bytes);  % The same as the above
a = vertcat(w(1:2).bytes);  % Vertical concatenation = [64; 128]
a = {w(1:2).bytes};         % Collects values in a cell array = {64, 128}
a = zeros(w(1:2).bytes);    % Creates a 64-by-128 matrix of zeroes
b = strcat(w.name);         % Horizontal concatenation of strings
b = strvcat(w.name);        % Vertical concatenation of strings
Run Code Online (Sandbox Code Playgroud)