How to efficiently generate a new array by indexing an array with another array

1 回表示 (過去 30 日間)
Is there a faster way to implement this loop, maybe vectorizing it?
for j = 1:m
C(:,j) = B(A(:,j,k),j);
end
where:
A is a l x m x n 3-D array of int from 1 to 4
B is a p x m 2-D array of doubles
C is a l x m 2-D array of doubles
l = order of 1000 ; m = order of 10 ; n = order of 100 ; p = 4
  2 件のコメント
Jan
Jan 2017 年 1 月 3 日
What is "k"?
Paolo Binetti
Paolo Binetti 2017 年 1 月 3 日
Sorry, I forgot: k is an index from 2 to n Indeed, the piece of code above is inside a "k" for-loop

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2017 年 1 月 3 日
L = l; %make it easier to distinguish lower-case L
C = B(sub2ind(size(B), A(:,:,k), repmat( 1:m, L, 1) ));
  2 件のコメント
Paolo Binetti
Paolo Binetti 2017 年 1 月 3 日
編集済み: Paolo Binetti 2017 年 1 月 3 日
Thank you: your solution is about 5-10 faster, which is good enough for me, as long as I compute
repmat( 1:m, L, 1)
only once and not inside the k-for-loop that contains this piece of code.
Walter Roberson
Walter Roberson 2017 年 1 月 4 日
Yes, that is a good idea, to move that computation outside the loop.
If you have R2016b or later it can be improved even more:
C = B( (A(:,:,k) - 1) * p + (1:m) )
and the 1:m could be assigned to a variable before the loop

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by