Fix an $n$ and an $m$ positive integers.I have some set of four $n\times n$ matrices $A$,$B$,$Y$,$Z$ (where $Z$ is the zero matrix). I'd like to input the $nm\times nm$ matrix of block matrices given by

ArrayFlatten [{{A,B,Z,...,Z},{Y,A,B,Z,...,Z}{Z,Y,A,B,Z...},...,{Z,...,Z,Y,A}}]

I have tried to do this using SparseArray using something like

  {i_, i_} -> A,
  {i_, j_} /; i - j == 1 -> B,
  {i_, j_} /; j - i == 1 -> Y,
  {i_, j_} /; Abs[i - j] > 1 -> Z
 }, {m, m}]

SparseArray does not seem to play nice with matrix inputs, and I do not think it is the right tool. I am told that things are not lists. What is an easy way to build block matrices out of rules (as Sparse Array does for matrices of numbers).


1 Answer 1


A = ConstantArray[1, {n, n}];
B = ConstantArray[2, {n, n}];
Y = ConstantArray[3, {n, n}];
Z = ConstantArray[0, {n, n}];

ClearAll[a, b, y, z]

m = 10;

mat=Normal@SparseArray[{{i_,i_}->a,{i_,j_}/;i-j==1->b,{i_,j_}/;j-i 1->y,{i_,j_}/;Abs[i-j]>1->z},{m,m}]

ArrayFlatten[mat /. {a -> A, b -> B, y -> Y, z -> Z}]
  • $\begingroup$ So the only thing different here is that you defined $A,B,Y,Z$ after defining the matrix and the use of Normal(is that necessary?)? I am not in a position to check that this works yet, but could you explain why it does? $\endgroup$
    – PVAL
    Feb 9, 2016 at 6:39
  • $\begingroup$ @PVAL I have edited my code. $\endgroup$ Feb 9, 2016 at 6:46
  • $\begingroup$ This certainly works. I am not sure why my original method doesn't. Thanks very much anyway. $\endgroup$
    – PVAL
    Feb 9, 2016 at 23:49
  • $\begingroup$ @PVAL SparseArray cannot insert matrices as elements. Lower case $a, b, y, z$ are only placeholders for $A, B, Y, Z$ and inside ArrayFlatten I replace them by rules. $\endgroup$ Feb 10, 2016 at 3:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.