# How to create a block diagonal matrix by repeating a submatrix $n$ times?

If there is a submatrix, let's call $P$:

$P=\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}$

And I want to have $n$, let's say $n=2$, such submatrices placed on the diagonal. The result is expected to look like:

$Q=\begin{pmatrix} 1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 1 & 1 \end{pmatrix}$

How do I write the code in Mathematica?

• This seems to be a special case of this question: How to form a block-diagonal Matrix from a list of matrices? Sep 8, 2014 at 18:22
• I noticed that thread. Well, it didn't say how to do that $n$ times. Sep 8, 2014 at 18:48
• Mainly I was just linking the question -- see "Linked" in column on the right -- so that others might easily find it. Some of the answers there are easily adapted (using ConstantArray[P, n] for the list of matrices), but special cases often also have special solutions. Sep 8, 2014 at 18:58

f1 = KroneckerProduct[IdentityMatrix[#], #2]&
f2 = SparseArray[{Band[{1, 1}, # Dimensions@#2] -> {#2}}] &
f3 = SparseArray[{Band[{1, 1}] -> ConstantArray[#2, #]}] &
f4 = ArrayFlatten[IdentityMatrix[#] /. 1 -> #2 ] &

p = Table[1, {2}, {2}];
f1[3, p]
f2[3, p] // Normal
f3[3, p] // Normal
f4[3, p]


all give

(* {{1,1,0,0,0,0},{1,1,0,0,0,0},
{0,0,1,1,0,0},{0,0,1,1,0,0},
{0,0,0,0,1,1},{0,0,0,0,1,1}} *)

• I posted basically the same thing here, but unfortunately the thread got closed.
– Jens
Sep 8, 2014 at 18:18
• @Jens, yes these are special cases of the answers in that Q/a and in the one linked there.
– kglr
Sep 8, 2014 at 18:58
mat[p_, n_] := ArrayFlatten[DiagonalMatrix[Array[1 &, n]] /. {1 -> p, 0 -> 0 p}]
p = {{1, 2}, {3, 1}};
mat[p, 3] // MatrixPlot • I'm slowly deleting my nearly identical answer now sobbing softly.
– kale
Sep 8, 2014 at 15:40
• @kale Soooo sorry :) Sep 8, 2014 at 15:42

Also useful here would be the Outer product:

p = ConstantArray[1, {2, 2}];
ArrayFlatten[Outer[Times, IdentityMatrix, p]]


which gives the desired output (displayed using MatrixForm) 