sparse( ix, jx, sx, rx, cx ) implausibly slow
古いコメントを表示
My understanding was that the five argument sparse call was designed to be a fast way of creating sparse matrices. But in some Kronecker product code I'm using (full code at the bottom, code indirectly derived from here), the profiler consistently reports it as the bottleneck.
Bizarrely, even doing sortrows( [ix,jx,sx] ) first does not speed up the call to sparse, despite the fact that this is basically the internal storage representation for sparse matrices used by Matlab.
Do you have any suggestions for speeding up the call to sparse?
Thanks in advance,
Tom
-------------------------------------------------------------------------------------------------
Suggested test:
n=300;A=sprandn(n,n,0.1);B=sprandn(n,n,0.1);
profile on;X=spkron(A,B);profile off;profile viewer
Required functions:
function X = spkron( A, B )
global spkron_use_mex
[I, J] = size(A);
[K, L] = size(B);
[ia,ja,sa] = find( A );
[ib,jb,sb] = find( B );
a = double( [ia,ja,sa] );
b = double( [ib,jb,sb] );
if isempty( spkron_use_mex )
[ ix, jx, sx ] = spkron_internal( K,a, L,b );
else
[ ix, jx, sx ] = spkron_internal_mex_mex( int32(K),a, int32(L),b );
end
X = sparse( ix, jx, sx, I*K, J*L );
end
function [ ix, jx, sx ] = spkron_internal( K,a, L,b )
% derived from alt_kron.m
ma = max( abs( a(:,3) ) ) * eps;
mb = max( abs( b(:,3) ) ) * eps;
a( abs(a(:,3))<mb, : ) = [];
b( abs(b(:,3))<ma, : ) = [];
ix = bsxfun(@plus,b(:,1),K*(a(:,1)-1).');
jx = bsxfun(@plus,b(:,2),L*(a(:,2)-1).');
sx = bsxfun(@times,b(:,3),a(:,3).');
sx( abs( sx ) < eps ) = 0;
end
2 件のコメント
Matt J
2014 年 8 月 5 日
In your suggested test, your "sparse" matrices are really rather dense (0.1). If this density is representative of the work you will be doing, and if the Kronecker products are going to be used for matrix-vector multiplications and mldivides, then you will get more speed using KRONPROD, even excluding the time to do the kron operation. Compare:
n=300;
A=sprandn(n,n,0.1);
B=sprandn(n,n,0.1);
x=rand(n^2,1);
K=kron(A,B);
tic
y=K*x;
toc
%Elapsed time is 0.179062 seconds.
tic;
Ko=KronProd({B,A});
y=Ko*x;
toc;
%Elapsed time is 0.008858 seconds.
Tom Holden
2014 年 8 月 5 日
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Sparse Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!