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$
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

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

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.