The increment of values ​​in a sparse matrix takes a very long time

I run the following code, where M is 200,000 ~ 200,000 sparse matrices, and points is a matrix of ~ 200,000 by 2

 inds=sub2ind(size(M),points(:,1),points(:,2)); M(inds)=M(inds)+1; 

the problem is that the second line takes a very long time (15-90 seconds). the operation takes longer depending on how many indices in inds are β€œnew” (that is, they do not yet matter in a sparse matrix)

is there a more efficient way to do this?

+4
source share
1 answer

Here is an idea:

 M = M + sparse(points(:,1),points(:,2),1,size(M,1),size(M,2),size(points,1)); 

Just to let you know,

S = sparse(i,j,s,m,n,nzmax) uses the vectors i , j and s to generate an m -by- n sparse matrix such that S(i(k),j(k)) = s(k) , with space allocated for nzmax nonzero values. The vectors i , j and s all the same length. Any elements of s that are equal to zero are ignored along with the corresponding values ​​of i and j . Any elements of s that have duplicate values ​​of i and j are added together.

For the curious:

 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 
+4
source

Source: https://habr.com/ru/post/1438204/


All Articles