在Matlab中用矩阵索引多维数组

时间:2014-01-29 11:03:22

标签: arrays matlab matrix multidimensional-array indexing

如何通过使用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循环

很容易
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

2 个答案:

答案 0 :(得分:3)

只需使用linear indexing

nElementsPerSlice = numel(indexes);

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

K = J(linearIndices);

答案 1 :(得分:1)

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

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