我如何通过使用 2d 矩阵按元素索引 nd 数组的维度,其中的条目表示要从中获取值的维度(表示切片或 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
最佳答案
只需使用 linear indexing :
nElementsPerSlice = numel(indexes);
linearIndices = (1:nElementsPerSlice) + (indexes(:)-1) * nElementsPerSlice;
K = J(linearIndices);
关于arrays - 在 Matlab 中用矩阵索引多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21429134/