Discretize differential equation by finite differences. What is the matrix?

I have a differential equation: $$-u''(x) + \sigma u'(x) = f(x), \quad 0<x<1$$ with boundary conditions $u(0) = \alpha$ and $u(1) = \beta$. I've discretized equation using symmetric (finite) differences: $$\frac{-u_{i-1} + 2u_i - u_{i+1}}{h^2} + \sigma \frac{u_{i+1} - u_i}{h} = f_i$$ If $n$ is the number of discretization points, $h = \frac{1}{n+1}$.

My question is how would I get that in a matrix form $Ax = f$ ?

• Is the question about discretizing your boundary conditions? Because otherwise you have a bunch of linear equations, so technically they are "already" in matrix form as soon as you "choose a basis" (which would obviously be corresponding to $\{ u_0, u_1, \cdots, u_n \}$ here). Can you develop on your issue? Where do you get stuck? Dec 22 '13 at 17:16
• No, I just want to see the matrix form. Because when I run some iterative numerical method (for example SSOR) I get different solution than when I run SOR. So now I'm getting confused if I wrote my matrix right. Dec 22 '13 at 17:21

I'm guessing you want $u(0) = \alpha$ and $u(1) = \beta$, not $u(a) = \beta$. Anyway, in the discretized version I'm guessing it means $u_0 = \alpha$ and $u_n = \beta$. So in fact you only want to solve for $u_1,\cdots, u_{n-1}$. I'll write $N = n+1$ just to not write $+1$'s everywhere. The first equation (for $u_1$) tells you that $$N^2(-u_0 + 2u_1 - u_2) + N \sigma (u_2 - u_1) = f_1,$$ i.e. $$(2N^2 - \sigma N) u_1 + (-N^2 + N \sigma)u_2 = f_1 + N u_0 = f_1 + N^2 \alpha.$$ For $u_{n-1}$, you have the equation $$N^2 (-u_{n-2} + 2u_{n-1} - u_n) + N \sigma (u_n - u_{n-1}) = f_{n-1},$$ i.e. $$(-N^2) u_{n-2} + (2N^2 - N \sigma) u_{n-1} = f_{n-1} + (N^2 - N \sigma) u_n = f_{n-1} + (N^2 - N \sigma) \beta.$$ For the other equations, you get $$N^2(-u_{i-1} + 2 u_i - u_{i+1}) + N\sigma (u_{i+1} - u_i) = f_i,$$ i.e. $$(-N^2) u_{i-1} + (2N^2 - N \sigma) u_i + (-N^2 + N \sigma) u_{i+1} = f_i.$$
To put all these equations in a clean form, let $$A = \begin{bmatrix} 2 & -1 & 0 & \cdots & & \\ -1 & 2 & -1 & 0 & \cdots & & \\ 0 & -1 & 2 & -1 & 0 & \cdots & \\ \vdots & \ddots & \ddots & \ddots & \ddots & \ddots \\ \\ & & & \ddots & \ddots & \ddots & \\ & & & & -1 & 2 & -1 \\ & & & & & -1 & 2 \end{bmatrix}$$ and $$B = \begin{bmatrix} -1 & 1 & & & \\ & -1 & 1 & & \\ & & \ddots & \ddots & \\ & & & -1 & 1 \\ & & & & -1 \end{bmatrix}.$$ Then letting $u = \begin{bmatrix} u_1 \\ u_2 \\ \vdots \\ u_{n-1} \end{bmatrix}$, you're looking to solve $$(N^2 A + N \sigma B) u = F,$$ where $$F = \begin{bmatrix} f_1 + N^2 \alpha \\ f_2 \\ \vdots \\ f_{n-2} \\ f_{n-1} + (N^2 - N \sigma) \beta \end{bmatrix}.$$ Hope that helps,
• @Caley : I explained in the answer why $N = n+1$! Do you see a problem in the answer? Apr 21 '17 at 10:20