What is the best way to construct a large tridiagonal matrix, in the following form (notably with alternating signs)?
$\mathbf M = \begin{pmatrix} 0 & a & 0 & 0 & 0 & \cdots \\ a & 0 & -a & 0 & 0&\cdots \\ 0 & -a & 0 & a & 0 &\cdots \\ 0 & 0 & a & 0 & -a &\cdots \\ \vdots & \vdots & \vdots & \vdots & \vdots & \ddots \end{pmatrix}$
I was using code like that shown below to produce constant sign diagonals of $a$ above and below the main diagonal for an $n\times n$ matrix.
DiagonalMatrix[Array[a &, n - 1], -1]
DiagonalMatrix[Array[a &, n - 1], 1]
Any help is appreciated.
Answer
Here is a way using Band:
SparseArray[{Band[{1, 2}, {4, 5}] -> {a, -a},
Band[{2, 1}, {5, 4}] -> {a, -a}}, {5, 5}] // MatrixForm
$$\left( \begin{array}{ccccc} 0 & a & 0 & 0 & 0 \\ a & 0 & -a & 0 & 0 \\ 0 & -a & 0 & a & 0 \\ 0 & 0 & a & 0 & -a \\ 0 & 0 & 0 & -a & 0 \\ \end{array} \right)$$
To make it easier to modify the size and the pattern of elements on the off-diagonals, I'd suggest something like this (incorporating J.M.'s suggestion):
With[{n = 7, pattern = {a, -a}},
SparseArray[{Band[{1, 2}, {-2, -1}] -> pattern,
Band[{2, 1}, {-1, -2}] -> pattern}, {n, n}]]
The negative indices are counted from the end, so that we don't need to use the dimension n in the Band specification. The reason I specify the beginning and end of each band is that only in this case will a cyclic repetition of pattern occur, as desired. If the end specification is omitted, pattern will only be used to fill the first few entries of the Band.
Comments
Post a Comment