# Constructing Tri-Diagonal Matrices

Fractional Calculus Course, we are instructed to create an $n \times n$ Tri-Diagonal matrix in the form of:

\begin{array} a A &= \begin{bmatrix} 2 & -1 & 0 & 0 & ... & 0 & 0 & 0\\ -1 & 2 & -1 & 0 & 0 & 0&... & 0 \\ 0 & -1 & 2 & -1 & 0& 0... & 0 & 0\\ 0 & 0 &-1 & 2 & -1 & ... & 0 & 0\\ &&&\vdots&&& \\ 0 & 0 & 0&... & 0 & -1 & 2 & -1\\ 0 & 0 & 0 & 0&... & 0 & -1 & 2 \\ \end{bmatrix} \end{array}

This is where my dilemma begins. I am not sure how to create this Tri-Diagonal Matrix. I came across the "SparseArray" command upon my research and it help me create a Tri-Diagonal Matrix, but I am having a hard time manipulating it to get the $-1, 2, -1$ pattern I am looking for.

mat = SparseArray[ {i_, j_} /; Abs[i - j] <= 1 :> 1, {10, 10}];
mat // MatrixForm


Above is the command I used for a $10 \times 10$ matrix. But the tri-diagonal entries were all 1's.

Thus my question is, how would I create the tri-diagonal matrix $n \times n$ I desire? Is there a way to create a function so I can simply manipulate the value of $n$ to get a new matrix without typing (or copy-pasting) the entire code again?

• Look up Band in the help files. Commented Sep 1, 2015 at 17:51
• Just curious ...What is a Fractional Calculus Course ? Commented Sep 1, 2015 at 18:19
• Fractional Calculus is a course that focuses on the applications of fraction derivatives and fraction integrals. So imagine taking half the derivative of f(x) or the two-third integral of f(x). I'm still new to the material so I can't give you a better example that this, sorry. Commented Sep 1, 2015 at 19:09
• Proposed duplicate: (13004). Related: (13796) Commented Sep 2, 2015 at 0:07

SparseArray[{{i_, i_} :> 2, {i_, j_} :> -1 /; Abs[i - j] == 1}, {10, 10}]  // MatrixForm


or

SparseArray[{Band[{1, 1}] -> 2, Band[{2, 1}] -> -1, Band[{1, 2}] -> -1}, {10, 10}] //
MatrixForm


The following is sometimes useful:

m = {{{a, b}, {b, a}}};
d = {10, 10};
SparseArray[{Band[{2, 2}, d] -> m, Band[{1, 1}, d] -> m}, d] // MatrixForm


Without SparseArray:

n = 10;
Total[
{DiagonalMatrix[Array[-1 &, n - 1], -1],
DiagonalMatrix[Array[2 &, n]],
DiagonalMatrix[Array[-1 &, n - 1], 1]}
]


Or strictly using Array:

Array[Which[#1 == #2, 2, Abs[#1 - #2] == 1, -1, True, 0] &, {10, 10}]


AND, what the heck? One more for more flexible applications:

a = {2, -1, -2, 3};
n = 10;
With[{a1 = PadRight[a, n]}, (Array[a1[[Abs[#1 - #2] + 1]] &, {n, n}])]//MatrixForm


• Your second snippet is what was usually done before SparseArray[] came along. Commented Sep 2, 2015 at 0:57

This should be faster (where n is your square dimension, e.g. 1000 for 1kX1k), easily extends to n-diagonal symmetric with no performance impact:

ToeplitzMatrix[PadRight[{2, -1}, n]]