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
Best Answer