MATLAB: Sparse Matrix – More Efficient Assignment Operation

diagonalsparsesparse assignmentsparse identitysparse matrix

I have a large sparse matrix for which I am attempting to assign certain segments (simplified example as per below snippet) to some identity matrices. The assignment method below is extremely inefficient, taking up a large amount of memory and too much time (10sec for example below on my server, but my real dataset is much bigger). Looking at the screenshot from taskmanager, we can see clearly a large spike in memory usage while the operation is being carried out.
For somebody used to dealing with large sparse matrices, there should be a more efficient way of carrying out such an assignment operation. Probably a pretty simple solution but I have little experience with sparse-matrix syntax.
A = sparse(20000,60000);
A(10001:end,20001:50000) = ([speye(10000,10000),-speye(10000,10000),speye(10000,10000)]);

Best Answer

That operation took less than 3 milliseconds on my machine.
The resulting array is 960,008 bytes.