2.43 Generate sparse matrix for the tridiagonal representation of second difference
operator in 1D
The second derivative \(\frac {d^{2}u}{dx^{2}}\) is approximated by \(\frac {u_{i-1}-2u_{i}+u_{i+1}}{h^{2}}\) where \(h\) is the grid spacing. Generate the \(A\)
matrix that represent this operator for \(n=4\) where \(n\) is the number of internal grid points on the
line
| Mathematica
numberOfInternalGridPoints = 4;
n = 3*internalGridPoints;
sp = SparseArray[{Band[{1,1}]->-2,
Band[{1,2}]->1,
Band[{2,1}]->1},
{n,n}]
Out[103]= SparseArray[<34>,{12,12}]
MatrixForm[sp]
|
\[ \left ( {\begin {array}{cccccccccccc} -2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 1 & -2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & -2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & -2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & -2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & -2 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & -2 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & -2 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & -2 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & -2 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & -2 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & -2 \\ \end {array}} \right ) \] |
| Matlab
internalGridPoints = 4;
n = 3*internalGridPoints;
e = ones(n,1);
sp = spdiags([e -2*e e], -1:1, n,n);
full(sp)
|
ans =
-2 1 0 0 0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