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 need to generate a very large sparse block matrix, with blocks consisting only of ones along the diagonal. I have tried several ways of doing this, but I seem to always run out of memory.

The fastest way of doing this that I've come up with so far is as follows:

(typically, I will need n to be at least 2500 and m of the order 50).

tmp= SparseArray[{}, {n,n}, 1];

  Table[If[i == j, tmp, 0], {i, m}, {j, m}]

Example when n=2, m=4:


The problem with this construction is that ArrayFlatten for some reason converts the result to a normal matrix, and I run out of memory. That is, when it works, this code computes the end result very quickly and the result does not take up much memory. At some specific number however, it suddenly crashes as the intermediate ArrayFlatten step clogs up the memory.

Any help will be greatly appreciated!

share|improve this question
@jVincent Full of 1's is the same as full of 0's when 1 is the default element – ssch Jan 22 '13 at 10:58

Maybe this ?

SparseArray[{Band[{1, 1}, Dimensions[tmp] {m, m}] -> {tmp}}, Dimensions[tmp] {m, m}]
share|improve this answer
Thanks a lot, this seems to solve the issue! – Jesper Jan 22 '13 at 11:13

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.