Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 7 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

 
discard

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.