1
$\begingroup$

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.

$\endgroup$

2 Answers 2

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

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

enter image description here

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

enter image description here

$\endgroup$
3
  • $\begingroup$ see also: How to form a block-diagonal matrix from a list of matrices? $\endgroup$
    – kglr
    Commented Sep 26, 2020 at 23:27
  • $\begingroup$ 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. $\endgroup$
    – xabdax
    Commented Sep 26, 2020 at 23:28
  • $\begingroup$ @xabdax, please see the corrected version. $\endgroup$
    – kglr
    Commented Sep 27, 2020 at 0:09
2
$\begingroup$
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
$\endgroup$
3
  • $\begingroup$ 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? $\endgroup$
    – xabdax
    Commented Sep 27, 2020 at 0:04
  • $\begingroup$ @xabdax Easy, simply set: mat[[-m;;-1,1;;n]]=0 $\endgroup$ Commented Sep 27, 2020 at 11:09
  • $\begingroup$ @xabdax Fixed. Or use Daniel's approach. $\endgroup$
    – Alan
    Commented Sep 27, 2020 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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