【问题标题】:Indexing multidimensional array with a matrix in Matlab在Matlab中用矩阵索引多维数组
【发布时间】:2014-02-21 03:23:11
【问题描述】:

如何通过使用 2d 矩阵来索引 nd-array 元素的维度,其中条目表示从哪些维度(表示切片或 2d 矩阵)获取值?

I=ones(2)*2;
J=cat(3,I,I*2,I*3);

indexes = [1 3 ; 2 2] ;

所以 J 是

J(:,:,1) =

 2     2
 2     2


J(:,:,2) =

 4     4
 4     4


J(:,:,3) =

 6     6
 6     6

使用 2 个 for 循环即可轻松工作

for i=1:size(indexes,1)
     for j=1:size(indexes,2)
        K(i,j)=J(i,j,indexes(i,j));
    end
end

产生期望的结果

K =

 2     6
 4     4

但是有没有一种矢量化/智能索引方式可以做到这一点?

%K=J(:,:,indexes)  --does not work

【问题讨论】:

    标签: arrays matlab matrix multidimensional-array indexing


    【解决方案1】:

    只需使用linear indexing:

    nElementsPerSlice = numel(indexes);
    
    linearIndices = (1:nElementsPerSlice) + (indexes(:)-1) * nElementsPerSlice;
    
    K = J(linearIndices);
    

    【讨论】:

      【解决方案2】:

      您可以使用sub2ind 将矩阵索引转换为线性索引

      ind = sub2ind( size(J), [1 1 2 2], [1 2 1 2], [1 3 2 2]);
      K = resize(J(ind), [2 2]);
      

      【讨论】:

        猜你喜欢
        • 2015-03-10
        • 2017-02-24
        • 2012-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-20
        • 2015-05-29
        相关资源
        最近更新 更多