在不循环访问matlab中访问多个结构字段

Acessing multiple structure fields in matlab without looping through it

我有一个 8x18 结构,每个单元格包含单个事件发生的列向量。我想从这些连接在单个数组中的一些字段中获取数据,而不必遍历它。我似乎找不到将我感兴趣的字段垂直连接到一个数组中的方法。

作为示例,我创建了以下结构,每个单元格出现 1 到 5 次:

s(62).vector(8,18).heading.occurrences=[1;2;3];
for i=1:62
    for j=1:8
        for k=1:18
            y=ceil(rand(1)*5);
            s(i).vector(j,k).heading.occurrences=rand(y,1);
        end
    end
end

现在,如果想要获得多个单元格中的所有出现,同时保持 i 恒定不变 i=1,则以下工作:

ss=s(1).vector([1 26 45]);                     
h=[ss.heading];            
cell2mat({h.occurrences}')

现在我想为 s 做同样的事情,例如 s([1 2 3]).vector([1 26 45]),那将如何工作?我试过 xx=s([1 2 3])yy=xx.vector([1 26 45]) 但这会产生错误:

Expected one output from a curly brace or dot indexing expression, but there were 3 results.

矢量运算也可以做到这一点吗?

很难向量化整个操作,但这应该可行。

% get vector field and store in cell array
s_new = { s(1:3).vector };

% now extract heading field, this is a cell-of-cells
s_new_heading = cellfun(@(x) { x.heading }', s_new, 'UniformOutput', false);

occurences = {};
for iCell = 1:length(s_new_heading)
    % use current cell
    cellHere = s_new_heading{iCell};

    % retain indices of interest, these could be different for each cell
    cellHere = cellHere([ 1 26 45 ]);

    % extract occurrences
    h = cellfun(@(x) x.occurrences, cellHere, 'UniformOutput', false);
    h_mat = cell2mat(h);

    % save them in cell array 
    occurences = cat(1, occurences, h_mat);
end

这是一个向量化的解决方案,可以为 s 和字段 vector:

使用索引向量
sIndex = [1 2 3];    % Indices for s
vIndex = [1 26 45];  % Indices for 'vector' field

v = reshape(cat(3, s(sIndex).vector), 144, []);
h = [v(vIndex, :).heading];
out = vertcat(h.occurrences);

它使用cat to concatenate all the vector fields into an 8-by-18-by-numel(sIndex) matrix, reshapes that into a 144-by-numel(sIndex) matrix, then indexes the rows specified by vIndex and collects their heading and occurrences fields, using vertcat instead of cell2mat