# How to build a tri-diagonal matrix [closed]

I have an algorithm that works for a Tri-Diagonal matrix in Mathematica, but I need a good way to build my starter matrix A. It's a 20 variable system (and will be a 200 variable system once I get it), so I need a loop to build my pieces. My outline looks like this right for the first 3 lines of my matrix;

h is a constant x1, x2, ... x3 are knowns, (x_n+1 = x_n + 1/h, I think I can write a loop for this...) I have a system Au = f, and need a way to build matrix A (a matrix of the coefficients below) in Mathematica.

-(2/h^2 +1)u1 +       (1/h^2 + x1/(2h))u2                                                                      = f1
(1/h^2 + x1/(2h))u1 - (2/h^2 +1)u2 +        (1/h^2 + x1/(2h))u3                                                = f2
(1/h^2 + x1/(2h))u2 - (2/h^2 +1)u3 +       (1/h^2 + x1/(2h))u4                           = f3
(1/h^2 + x1/(2h))u3 - (2/h^2 +1)u4 +       (1/h^2 + x1/(2h))u5     = f4
.
.
.
(1/h^2 + x1/(2h))u17 - (2/h^2 +1)u18 +       (1/h^2 + x1/(2h))u19    = f18
(1/h^2 + x1/(2h))u18 - (2/h^2 +1)u19          = f19


where u = {u1, u2, ..., u19} is the vector I am solving for.

Some advice for some sort of loop to build this main matrix would be very helpful. I have had difficulty thus far using this forum and it may not be what I think it is.

• Looks like a job for SparseArray and Band. Oct 5, 2020 at 5:09

Try

n = 20;
M = Table[If[i == j, -(1 + 2/h^2), If[Abs[i - j] == 1, 1/h^2 + x1/(2 h), 0]], {i, 1, n}, {j, 1, n}]


or also

M = SparseArray[{Band[{1, 1}] -> -(1 + 2/h^2), Band[{2, 1}] -> 1/h^2 + x1/(2 h), Band[{1, 2}] -> 1/h^2 + x1/(2 h)}, {n, n}]


NOTE

Now for $$x_k, k=1,\cdots, n$$ we can use

M = SparseArray[{{i_, i_} -> -(1 + 2/h^2), {n, n - 1} -> 1/h^2 + x[n - 1]/(2 h), {i_, j_} /; Abs[i - j] == 1 -> 1/h^2 + x[Min[i, j]]/(2 h)}, {n, n}, 0.]

• This is awesome, I think SparseArray is definitely the functionality that I want. My issue now is that I had my matrix setup wrong, and I also need to be changing the index on my x values in each row, so that the first row has x1, the second row has x2, the third row uses x3 and so forth. I tired embedding a SparseArray into a loop For[i = 0, i <= n, i++, ...] and then changing x1 to x[i], but it still repeats. Before this in the code I have For[i = 0, i <= n, i++, x[i] = i*h] to run through my x values. Thoughts? Oct 6, 2020 at 0:28
• Please. See attached note. Oct 6, 2020 at 8:06