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 likeW
orA
. $\endgroup$MapAt[0.&, K, list1]
(similarly for otherMapAt
s)? $\endgroup$k[[bc, ;;]] = 0.; k[[;; , bc]] = 0.; k = ReplacePart[k, Transpose@{bc, bc} -> 1.];
on my computer takes around0.05
seconds . AlsoRandomInteger[5552, ...]
coud possibly generate 0 element which leads to error in replacing, use{1, 5552}
instead. $\endgroup$list2
is unnecessary. Instead ofMapAt[0.&, k, list2]
, which is slow, you could do this:k = Transpose[k]; k = MapAt[0.&, k, list1]; k = Transpose[k];
, which is fast. $\endgroup$