# Create block matrix with secondary diagonals using Band function

Given matrices m1, ... , mk and matrices n1, ... , nk-1, I would like to define a block matrix $$m=\left( \begin{array}{rrrr}m1 & n1 & 0 & 0 \\0 & m2 & \ddots & 0 \\\vdots & \ddots & \ddots & nk-1 \\0 & \dots & 0 & mk \\\end{array}\right)$$ with blocks mi on the diagonal and blocks nj on the secondary diagonal. The sizes of the matrices are compatible.

I would like to define m as an sparse array using the Band function, but I didn't manage. Is it possible?

Edit: Before, I called the matrices m[i] and n[j] which was misleading, see kglr's answer

• any restrictions on Dimensions of mi's and ni's? – kglr Mar 16 at 11:52
• @kglr actually, it would be best if the function figures out the dimensions by itself – Bipolar Minds Mar 16 at 11:58
• so Dimensions of m1 and m2 are not necessarily the same (similarly for n1 and n2)? – kglr Mar 16 at 12:01
• @kglr no, they can be arbitrary – Bipolar Minds Mar 16 at 12:02
• @kglr the only assumption is that they are compatible – Bipolar Minds Mar 16 at 12:03

Update:

ClearAll[sA]
sA = SparseArray[{Band[{1, 1}] -> #, Band[{1, 1 + Last@Dimensions[#[]]}] -> #2}] &;


Example:

SeedRandom
k = 4;
{rowdims, coldims} = RandomInteger[{2, 4}, {2, k}];

ClearAll[m1, m2, m3, m4, n1, n2, n3, ma, mb, mc, md, na, nb, nc];

ms = {m1, m2, m3, m4} = MapThread[Array[Function[{x, y}, Subscript[#, x, y]], #2] &,
{{ma, mb, mc, md}, Transpose[{rowdims, coldims}]}];

ns = {n1, n2, n3} = MapThread[Array[Function[{x, y}, Subscript[#, x, y]], #2] &,
{{na, nb, nc}, Transpose[{Most@rowdims, Rest@coldims}]}];

sA[ms, ns] // MatrixForm sA[Map[Style[#, Blue] &, ms, {-2}], Map[Style[#, Red] &, ns, {-2}]] // MatrixForm sa[k_Integer] := SparseArray[{Band[{1, 1}] -> Array[m, k],

$$\left( \begin{array}{ccccc} m(1) & n(1) & 0 & 0 & 0 \\ 0 & m(2) & n(2) & 0 & 0 \\ 0 & 0 & m(3) & n(3) & 0 \\ 0 & 0 & 0 & m(4) & n(4) \\ 0 & 0 & 0 & 0 & m(5) \\ \end{array} \right)$$
• Hm, but if I replace Array[m,k] and Array[n,k-1] now by actual lists of matrices m and n and fix k accordingly, then the MatrixForm doesn't work anymore – Bipolar Minds Mar 16 at 11:29
• I think it was my fault, I shouldn't have called the matrices m[i] and n[j] in the original post, but rather mi and nj – Bipolar Minds Mar 16 at 11:37