Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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}];
  {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.)

share|improve this question
up vote 9 down vote accepted

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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