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 件)
Bruno Luong
2018 年 10 月 3 日
編集済み: Bruno Luong
2018 年 10 月 3 日
C = A(B+reshape(0:numel(B)-1,size(B))*size(A,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!