# Concatenate matrices in a specific way

Is there an elegant way to start with a matrix of the form

$$A = (B,C)$$ where B and C have dimensions n x m, and construct a large matrix that looks like

$$\begin{pmatrix} B & C & \mathbf{0} & \mathbf{0}&\ddots&\mathbf{0}\\ \mathbf{0} & B & C & \mathbf{0}&\ddots&\mathbf{0}\\ \ddots &\ddots &\ddots &\ddots &\ddots&\mathbf{0}\\ \mathbf{0} &\mathbf{0} &\mathbf{0} &\mathbf{0} & \mathbf{0} & B \end{pmatrix}$$

where $$\mathbf{0}$$ is the zero matrix with the same dimensions as B and C? I would like to keep the size of this matrix variable.

dims = {3, 2};
{bB, cC} = Array[#, dims] & /@ {b, c};

Row[MatrixForm /@ {bB, cC}, Spacer[10]]


k = 4;
kdims = k dims;
SparseArray[{Band[{1, 1}, kdims] -> {bB},
Band[{1, dims[[2]] + 1}, kdims] -> {cC}}, kdims] // MatrixForm


• – kglr Sep 26 '20 at 23:27
• Hey thanks for the answer, but I was looking for a solution in which matrices C and B are on top of each other. That is the reason why I split A into two matrices to begin with. – xabdax Sep 26 '20 at 23:28
• @xabdax, please see the corrected version. – kglr Sep 27 '20 at 0:09
build[mB_, mC_, nZs_] := With[{
m = Length@mB,
n = Length@mB[[1]]},
Module[{base, len},
len = n*(2 + nZs);
base = PadRight[ArrayFlatten[{{mB, mC}}], {m, len}, 0];
Catenate@Table[PadLeft[base[[All,;; n*(2 + nZs - i)]], {m, len}, 0], {i,0, nZs + 1}]
]]


For example:

m = 3
n = 2
mB = RandomInteger[100, {m, n}]
mC = RandomInteger[100, {m, n}]
nZs = 3
build[mB, mC, nZs] // MatrixForm

• Hey thanks for that answer. It seems that there is still one matrix block in the lower left corner where there should be only zeros. Is there any way to get rid of that matrix block? – xabdax Sep 27 '20 at 0:04
• @xabdax Easy, simply set: mat[[-m;;-1,1;;n]]=0 – Daniel Huber Sep 27 '20 at 11:09
• @xabdax Fixed. Or use Daniel's approach. – Alan Sep 27 '20 at 14:15