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

4

如何使用一个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

使用两个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个回答

3

只需使用线性索引

nElementsPerSlice = numel(indexes);

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

K = J(linearIndices);

1
你可以使用 sub2ind 将矩阵索引转换为线性索引。
ind = sub2ind( size(J), [1 1 2 2], [1 2 1 2], [1 3 2 2]);
K = resize(J(ind), [2 2]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接