From: H on
Try this:

http://www.mathworks.com/matlabcentral/fileexchange/23488-sparse-sub-access

Worked like a charm for me when I had the exact same problem...
From: Pat Quillen on
"Franz-Josef " <franz.falkner(a)uibk.ac.at> wrote in message <htao72$etb$1(a)fred.mathworks.com>...
> Hello everybody!
> My question is about sparse matrices.
> For my FE-Program, written in Matlab, I want to set values of
> certain columns and rows of a sparse matrix zero. For example:
> K(c,:) = 0, where c is a vector. If K is a full matrix, this operation
> takes only a second for matrix sizes up to 10000. If K is a sparse
> matrix this operation takes over one hour!
> What possibilities exist, to speed up this operation with sparse matrices?
> Thanks a lot for your suggestions!
> FJ

FJ:

With MATLAB 7.10 (R2010a) assignment into rows of sparse matrices is generally much faster than in previous releases. For example, on a 64 bit Linux machine, R2009b gives:

>> version
ans =
7.9.0.529 (R2009b)
>> A = sprand(10000,10000,0.01);
>> p = randi(10000,1,1000);
>> tic; A(p,:) = 0; toc
Elapsed time is 3.750562 seconds.

On the other hand, we see for R2010a:

>> version
ans =
7.10.0.499 (R2010a)
>> A = sprand(10000,10000,0.01);
>> p = randi(10000,1,1000);
>> tic; A(p,:) = 0; toc
Elapsed time is 0.055481 seconds.

Of course, the amount of time the operation takes is proportional to the size of the matrix and the number of nonzeros, but the R2010a version is much improved. The improvement is not limited to assigning in scalars:

>> version
ans =
7.9.0.529 (R2009b)
>> A = sprand(10000,10000,0.01);
>> p = randi(10000,1,1000);
>> B = sprand(1000,10000,0.1);
>> tic; A(p,:) = B; toc
Elapsed time is 5.701408 seconds.

>> version
ans =
7.10.0.499 (R2010a)
>> A = sprand(10000,10000,0.01);
>> p = randi(10000,1,1000);
>> B = sprand(1000,10000,0.1);
>> tic; A(p,:) = B; toc
Elapsed time is 0.124965 seconds.

Echoing other posters, one should always favor working columnwise in MATLAB (both with sparse and dense matrices alike) but we are working hard to make natural expressions (such as A(p,:) = B) have the best possible performance. Look for further improvements to the performance of sparse matrix indexing with coming releases.

Finally, it is worth noting that assigning zeros into a sparse matrix will likely be slower than assigning zeros into a dense matrix of the same size since in the case of the sparse matrix, elements typically have to be moved around to squeeze out newly introduced zeros.

Take care.
Pat.