3
$\begingroup$

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?

$\endgroup$
5
  • 4
    $\begingroup$ 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. $\endgroup$
    – Roman
    Commented Feb 10, 2022 at 8:03
  • 3
    $\begingroup$ you probably meant MapAt[0.&, K, list1] (similarly for other MapAts)? $\endgroup$
    – kglr
    Commented Feb 10, 2022 at 8:21
  • 3
    $\begingroup$ 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. $\endgroup$
    – Ben Izd
    Commented Feb 10, 2022 at 9:03
  • $\begingroup$ Thanks, Ben Izd! It's taking 0.007 sec on my system. $\endgroup$ Commented Feb 10, 2022 at 14:06
  • $\begingroup$ 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. $\endgroup$
    – LouisB
    Commented Feb 16, 2022 at 10:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.