# Fastest Way to make rows and columns zero and corresponding (i,i) element 1 of a large Sparse Matrix

I have a 5552 by 5552 sparse matrix:

K = SparseArray[
{
Band[{1, 1}] -> 0.2,
Band[{2, 1}] -> 0.5,
Band[{1, 2}] -> 1.,
Band[{300, 1}] -> 1.,
Band[{1000, 1}] -> 1.
}, {5552, 5552}];


An array is given:

bc = RandomInteger[5552, {542}];


Now my goal is to take each entry of bc and make the corresponding row and column of K zero with [i,i] element as 1.

I am doing it this way:

list1 = Map[{#, All} &, bc];
list2 = Map[{All, #} &, bc];
list3 = Map[{#, #} &, bc];

MapAt[0., K, list1]; // AbsoluteTiming
(* Out: {1.38702, Null} *)

MapAt[0., K, list2]; // AbsoluteTiming
(* Out: {181.601, Null} *)

MapAt[1., K, list3]; // AbsoluteTiming
(* Out: {1.24544, Null} *)


It is taking 181 sec to make rows 0. Is there a faster way to do this?

• K is not a good symbol for a variable, it has some internal special meaning. Notice that its color is different from other variables like W or A. Commented Feb 10, 2022 at 8:03
• you probably meant MapAt[0.&, K, list1] (similarly for other MapAts)?
– kglr
Commented Feb 10, 2022 at 8:21
• Try k[[bc, ;;]] = 0.; k[[;; , bc]] = 0.; k = ReplacePart[k, Transpose@{bc, bc} -> 1.]; on my computer takes around 0.05 seconds . Also RandomInteger[5552, ...] coud possibly generate 0 element which leads to error in replacing, use {1, 5552} instead. Commented Feb 10, 2022 at 9:03
• Thanks, Ben Izd! It's taking 0.007 sec on my system. Commented Feb 10, 2022 at 14:06
• Actually, list2 is unnecessary. Instead of MapAt[0.&, k, list2], which is slow, you could do this: k = Transpose[k]; k = MapAt[0.&, k, list1]; k = Transpose[k];, which is fast. Commented Feb 16, 2022 at 10:02