Setting row of sparse matrix to zero in matlab
Alec Jacobson
May 24, 2013
I wanted to set a whole row of a sparse matrix A to zero:
A = sparse(1e8,1e8);
tic;
A(r,:) = 0;
toc
But this was rather slow. About 1.7 seconds.
Turns out all rows and columns are not created equal in matlab. Because of how matlab stores sparse matrices it's much faster to set a whole column to zero:
tic;
A(:,c) = 0;
toc
This is about 0.0002 seconds.
So if you can refactor your code you're better off messing with columns. If you can't refactor, you might think it would be fast to transpose before and after setting a row to zero:
tic;
A = A';
A(:,r) = 0;
A = A';
toc
But this helps not at all. It seems transposes are just stored as flags, which is usually a good thing. But here it means we don't gain anything, since after the transpose, now rows the cheap route. This also implies that refactoring could be nontrivial.
One might also think you could first find all the non-zero entries and then set them each to zero. But just the rowwise find is expensive:
tic;find(A(10,:));toc
~1 second
In fact just the row-wise access is expensive
tic;A(10,:);toc
~1 second
Seems like there's no happy answer.