Vectorization of indexing of each row of a matrix by a corresponding row of another matrix?

1 回表示 (過去 30 日間)
I have a routine that creates a new matrix A from an old matrix M by using another matrix I as a source for indexing. More specifically, each row of A is obtained by indexing a row of M by the corresponding row from I (see code example below with small matrix sizes). I would like to accelerate/vectorize this routine for better performance if that's possible. I was thinking of somehow using a combination of linear and logical indexing for M and then reshaping back to A, but I don't immediately see how to generate appropriate index vectors.
I also have the analogous problem for 3D-matrices, where I have to loop through two indexes (I could merge both loops into a single one, but the problem with the size of the loop remains).
I_range = 10; % index range for the 2nd dimension of M
l = 5; % 1st dimension for I and M
w = 4; % 2nd dimension for A, and hence for I
M_range = 20; % sets value range for M
I = randi(I_range,l,w);
M = randi(M_range,l,I_range);
% need to accelerate the following routine:
A = zeros(l,w,'double'); % allocate
for j=1:l
A(j,:) = M(j,I(j,:));
end

採用された回答

KSSV
KSSV 2022 年 2 月 3 日
I_range = 10; % index range for the 2nd dimension of M
l = 5; % 1st dimension for I and M
w = 4; % 2nd dimension for A, and hence for I
M_range = 20; % sets value range for M
I = randi(I_range,l,w);
M = randi(M_range,l,I_range);
% With loop
% need to accelerate the following routine:
A = zeros(l,w,'double'); % allocate
for j=1:l
A(j,:) = M(j,I(j,:));
end
% No loop
row = repmat((1:size(I,1))',1,size(I,2)) ;
row = row(:) ;
col = I(:) ;
idx = sub2ind(size(M),row,col) ;
A1 = reshape(M(idx),[],w) ;
isequal(A,A1)
ans = logical
1

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by