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!