8
$\begingroup$

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.)

$\endgroup$
12
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.