フィルターのクリア

Sparse for element by element operation

7 ビュー (過去 30 日間)
D_coder
D_coder 2018 年 9 月 15 日
コメント済み: D_coder 2018 年 9 月 16 日
If we want to perform the product of two sparse matrices or sparse and a full matrix , sparse function is very useful as it avoids multiplications with zero. However when we do element by element multiplication of two sparse matrices or a sparse matrix and a full matrix it is observed that it takes a considerable amount of time as compared to the multiplication of full matrices. Here is a concrete example
A = sprand(1000,1000,0.005);
B = rand(1000,1000);
Af = full(A);
timeit(@() Af.*B)
ans =
5.1227e-04
timeit(@() A.*B)
ans =
0.0011
How do I tackle this issue when I am looking for a considerable lower time than the multiplication of two full matrices?

回答 (2 件)

Bruno Luong
Bruno Luong 2018 年 9 月 15 日
編集済み: Bruno Luong 2018 年 9 月 15 日
A = sprand(1000,1000,0.005);
B = rand(1000,1000);
tic
Af = full(A);
AB=Af.*B;
toc % Elapsed time is 0.011628 seconds.
tic
AB=A.*B;
toc % Elapsed time is 0.004143 seconds.
Recommended solution
tic
[i,j,a]=find(A);
b=B(sub2ind(size(B),i,j));
AB=sparse(i,j,a.*b);
toc % Elapsed time is 0.001570 seconds.
  3 件のコメント
Bruno Luong
Bruno Luong 2018 年 9 月 16 日
編集済み: Bruno Luong 2018 年 9 月 16 日
Why you think my code assumes some loop or not ? It just carries out the element-wise product A.*B like other methods.
D_coder
D_coder 2018 年 9 月 16 日
It's not your code that assumes a loop , my code has a loop that runs for 9000 times and I have already tried doing sparse inside it , it gives me a worse performance than the original thing without sparse

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


Bruno Luong
Bruno Luong 2018 年 9 月 15 日
編集済み: Bruno Luong 2018 年 9 月 15 日
You might also interested in this FEX
[i,j]=find(A);
b=B(sub2ind(size(B),i,j));
AB=setsparse(A,i,j,b,@times);

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by