interesting matrix indexing question without for loops
1 次查看(过去 30 天)
显示 更早的评论
size(matrixA)=[b,n,m]
size(matrixB)=[n,m]
how can I create
matrixC(i,j)=matrixA(matrixB(i,j),i,j)
without using for-loops? What is this kind of indexing called? Thanks!
0 个评论
采纳的回答
Stephen23
2018-10-3
编辑:Stephen23
2018-10-3
A = reshape(1:6*3*2,6,3,2);
B = [6,1;4,3,;5,2];
% Solution with loops:
for ii = 1:size(B,1)
for jj = 1:size(B,2)
C(ii,jj) = A(B(ii,jj),ii,jj);
end
end
% Solution with SUB2IND:
S = size(B);
[I,J] = ndgrid(1:S(1),1:S(2));
X = sub2ind(size(A),B,I,J);
D = A(X)
% Compare:
isequal(C,D)
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!