How to cite the row of the matrix by vectorization?

1 回表示 (過去 30 日間)
wei zhang
wei zhang 2019 年 9 月 3 日
コメント済み: wei zhang 2019 年 9 月 4 日
Hi,
I have a problem in speeding my code. In my code, there is a step as below,
a=repmat(1:6,3,1)';
index=[1:3;2:4];
result=zeros(3,3,size(index,1));
for i=1:size(index,1)
result(:,:,i)=a(index(i,:),:)
end
In practice, the matrix a and index are very large n*3 matrix. a is the node coordinates and the index is the triangle face index of the node. The surface is too big. So I really need to speed this loop. I have an idea that vectorization could make the code faster. But I could not get the ideal output result, even with some matrix "resize" or matrix rotation functions, like "resize" or "reshape". I am very thankful for any suggestion.

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 9 月 3 日
編集済み: Andrei Bobrov 2019 年 9 月 3 日
For large matrices, the cycle may be faster.
a = repmat(1:6,3,1)';
index = [1:3;2:4];
si = size(index);
result = permute(reshape(a(index',:),si(2),si(1),[]),[1,3,2]);
  1 件のコメント
wei zhang
wei zhang 2019 年 9 月 4 日
Thank you for your answer!
I just record the speed comparision here for others. My 'a' matrix is 188802*3, and 'index' is 377644*3. The time with the previous loop is approximately 0.9 s; the time use this answer is 0.08s. The vectorization method is obviously much faster.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by