9

I have a matrix of sparse matrices that I want to convert to a sparse block matrix. So, basically I want what ArrayFlatten does, except that I want the output to be sparse. So e.g.:

sp = SparseArray[{{2, 2} -> 1.}, {50, 50}];
sparseArrayFlatten[
 {
  {sp, 0},
  {0, -sp}
  }]

should return SparseArray[{{2, 2} -> 1., {52, 52} -> -1., {_, _} -> 0},{100,100}].

Currently, I use SparseArray@ArrayFlatten[...], but for large matrices, this is inefficient.

(Sometimes ArrayFlatten does return a sparse array, but I haven't completely figured out when. For example, if I remove the - sign above, or if I use -> 1 instead of -> 1., I get a sparse result.)

Niki Estner
  • 36,101
  • 3
  • 92
  • 152

1 Answers1

13

Everything needs to be of the same precision including the background element.

Then this:

sp = SparseArray[{{2, 2} -> 1.}, {50, 50}, 0.];
ArrayFlatten[{{sp, 0.}, {0., -sp}}]

will return a SparseArray without creating a dense matrix first.

user21
  • 39,710
  • 8
  • 110
  • 167