Reputation: 1386
i'm running the following code, where M
is a ~200,000 by ~200,000 sparse matrix and points
is ~200,000 by 2 matrix
inds=sub2ind(size(M),points(:,1),points(:,2));
M(inds)=M(inds)+1;
the problem is that the second line takes very long to run (15-90 seconds).
the operation takes longer depending on how many of the indices in inds
are 'new' (i.e. that don't already have a value in the sparse matrix)
is there a more efficient way to do this?
Upvotes: 4
Views: 378
Reputation: 34601
Here's an idea:
M = M + sparse(points(:,1),points(:,2),1,size(M,1),size(M,2),size(points,1));
S = sparse(i,j,s,m,n,nzmax)
uses vectorsi
,j
, ands
to generate anm
-by-n
sparse matrix such thatS(i(k),j(k)) = s(k)
, with space allocated fornzmax
nonzeros. Vectorsi
,j
, ands
are all the same length. Any elements ofs
that are zero are ignored, along with the corresponding values ofi
andj
. Any elements ofs
that have duplicate values ofi
andj
are added together.
M = sprand(200000,200000,1e-6);
points = [randperm(200000) ; randperm(200000)]'; %'//Initialization over
Mo = M;
tic;
inds=sub2ind(size(Mo),points(:,1),points(:,2));
Mo(inds) = Mo(inds)+1;
toc
tic;
M = M + sparse(points(:,1),points(:,2),1,size(M,1),size(M,2),size(points,1));
toc
Upvotes: 4