Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to set many values of sparse matrix

I have a sparse 5018x5018 matrix in MATLAB, which has about 100k values set to 1 (i.e., about 99.6% empty).

I'm trying to flip roughly 5% of those zeros to ones (i.e., about 1.25m entries). I have the x and y indices in the matrix I want to flip.

Here is what I have done:

sizeMat=size(network);
idxToReplace=sub2ind(sizeMat,x_idx, y_idx);
network(idxToReplace) = 1;

This is incredibly slow, in particular the last line. Is there any way to make this operation run noticeably faster, preferably without using mex files?

like image 672
Jeff Avatar asked Nov 19 '25 05:11

Jeff


1 Answers

This should be faster:

idxToReplace=sparse(x_idx,y_idx,ones(size(x_idx),size(matrix,1),size(matrix,2)); % Create a sparse with ones at locations
network=network+idxToReplace; % Add the two matrices

I think your solution is very slow because you create a 1.26e6 logical array with your points and then store them in the sparse matrix. In my solution, you only create a sparse matrix and just sum the two.

like image 60
Adriaan Avatar answered Nov 22 '25 04:11

Adriaan