TransWikia.com

Creating a block diagonal matrix when the submatrices in the diagonal are unknown

Mathematica Asked by arod on February 5, 2021

Let us assume that we have an integer $j$ $(j=1,2,…,k)$ and that for every $j$ is generated a matrix $P$ of dimensions $j$x$j$ . For example, if $j=1$ then $P=(-2)$.

If $j=2$ then

$$R = begin{pmatrix} -2 & 1 0 & -2 end{pmatrix}$$

If $j=3$ then

$$R = begin{pmatrix} -2 & 1 &0 0 & -2 & 1 0 & 0 & -2 end{pmatrix}$$
and so forth.

I want to construct a block diagonal matrix $J$ with all the matrices $P$ (which have been generated before, in the iteration of $j$) in the diagonal elements. I suppose that ArrayFlatten and DiagonalMatrix should be used but I don’t know in what way. Any help appreciated, thank you.

4 Answers

SparseArray[Band[{1, 1}] -> (P /@ Range[n])]

If P produces SparseArrays, this does not seem to work. Then one can either convert to dense arrays with Normal like this

SparseArray[Band[{1, 1}] -> (Normal@*P /@ Range[n])]

or one can emply the undocumented function SparseArray`SparseBlockMatrix as follows:

SparseArray`SparseBlockMatrix[{#, #} -> P[#] & /@ Range[5]]

Answered by Henrik Schumacher on February 5, 2021

Like this?

Clear["`*"];
jordan[j_ /; j >= 2] := 
 SparseArray[{Band[{1, 1}] -> -2, Band[{1, 2}] -> 1}, {j, j}]
jordan[j_ /; j == 1] := {{-2}};
n = 5;
SparseArray[{Band[{1, 1}] -> Table[jordan[j] // Normal, {j, 1, n}]}, 
 Sum[j, {j, 1, n}]]
% // MatrixForm

Answered by cvgmt on February 5, 2021

Table[Which[x + 1 == y, 1, x == y, -2, True, 0], {x, 0, #}, {y, 0, #}] &@5

{{-2, 1, 0, 0, 0, 0}, {0, -2, 1, 0, 0, 0}, {0, 0, -2, 1, 0, 0}, {0, 0, 0, -2, 1, 0}, {0, 0, 0, 0, -2, 1}, {0, 0, 0, 0, 0, -2}}

Answered by wuyudi on February 5, 2021

"I suppose that ArrayFlatten and DiagonalMatrix should be used but I don't know in what way."

Other answers show that ArrayFlatten or DiagonalMatrix are not needed. But, in case you wish to use them, here is a way:

P[n_] /; n > 1 := -2 IdentityMatrix[n] + 
   DiagonalMatrix[ConstantArray[1, n - 1], 1];
P[1] = {{-2}};

n = 5;

MatrixForm @ 
 ArrayFlatten[DiagonalMatrix[Range @ n] /. i_Integer?Positive :> P @ i]

enter image description here

You can also use ArrayFlatten + IdentityMatrix:

plist = P /@ Range[n];

MatrixForm @ 
 ArrayFlatten[IdentityMatrix[n] /. 1 :> Last[plist = RotateLeft[plist]]]
 same picture

Both methods work with arbitrary list of matrices,

Q[{n_, m_}] := Array[Subscript[x, Row @ {##}] &, {n, m}];

SeedRandom[1]
qlist = Table[Q @ RandomInteger[{2, 6}, 2], n];

MatrixForm @ 
 ArrayFlatten[DiagonalMatrix[Range @ n] /. i_Integer?Positive :> qlist[[i]]]

enter image description here

MatrixForm @ 
 ArrayFlatten[IdentityMatrix[n] /. 1 :> Last[qlist = RotateLeft[qlist]]]
 same picture

Answered by kglr on February 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP