# How can I generate a tridiagonal block matrix? [duplicate]

$$\begin{pmatrix}C&D&&&&\\D&C&D&&&\\&\ddots&\ddots&\ddots&&\\&&&D&C&D\\&&&&D&C\end{pmatrix}$$

I want to generate a block tridiagonal matrix like the one depicted above, where $$C$$ and $$D$$ are both $$2\times 2$$ matrices. For example, I want a matrix with 5 $$C$$ entries. I tried many functions, but I have failed.

• m=SparseArray[{Band[{1, 1}] -> c, Band[{1, 2}] -> d, Band[{2, 1}] -> d}, {5, 5}]; m // MatrixForm Jun 11, 2022 at 9:11
• Another possibility is ToeplitzMatrix Jun 11, 2022 at 9:12
• I'll write a more detailed answer later unless someone beats me to it; for now, look at SparseArray[{Band[{4, 1}] -> ConstantArray[HilbertMatrix[3], 4], Band[{1, 1}] -> ConstantArray[ToeplitzMatrix[3], 5], Band[{1, 4}] -> ConstantArray[HilbertMatrix[3], 4]}]. Jun 11, 2022 at 9:43
• Courtesy of @yarchik, you can also use ToeplitzMatrix[{c, d, 0, 0, 0}] /. {c -> {{1, 1}, {1, 1}}, d -> {{2, 2}, {2, 2}}} // ArrayFlatten. The key is ArrayFlatten. Jun 11, 2022 at 10:27

It must be many ways to do this,here we provide one way.

Clear[matrix];
matrix = (SparseArray[{Band[{1, 1}] -> c, Band[{1, 2}] -> d,
Band[{2, 1}] -> d}, {8, 8}] //
Normal) /. {c -> {{x, y}, {z, w}}, d -> {{m, n}, {p, q}}} //
ArrayFlatten;
matrix // MatrixForm


The matrix you have is block tridiagonal and block Toeplitz.

I'll give two methods: one that uses nothing but documented functionality, and one that uses undocumented functionality.

First up is an extension of the method I gave in the comments, which hinges on the ability of SparseArray[] + Band[] to handle a list of matrices (of conforming dimensions):

cmat = Array[C, {2, 2}];
dmat = Array[\[FormalCapitalD], {2, 2}];
With[{m = 5, k = Length[cmat]},
bigMat = SparseArray[{Band[{k + 1, 1}] -> ConstantArray[dmat, m - 1],
Band[{1, 1}] -> ConstantArray[cmat, m],
Band[{1, k + 1}] -> ConstantArray[dmat, m - 1]}]];

MatrixForm[bigMat]


The important part here is the specification of Band[] for the off-diagonal blocks, which depends on the sizes of the blocks.

For the method using undocumented functions, here is one that uses SparseArraySparseBlockMatrix[], which has previously featured in past answers on block matrices (here I use the same definitions as above):

With[{m = 5, k = Length[cmat]},
bigMat = SparseArraySparseBlockMatrix[
Join[MapIndexed[Join[#2, #2] -> #1 &, ConstantArray[cmat, m]],
MapIndexed[Join[#2, #2 + 1] | Join[#2 + 1, #2] -> #1 &,
ConstantArray[dmat, m - 1]]]]];


which should give the same matrix.

(Perhaps someday, Mathematica will have better handling of block matrices.)