Search code examples
pythonoptimizationscipysparse-matrixlinear-algebra

Linear algebra with a sparse triagonol marix


I have a tridiagonal matrix A which I want to make a sparse matrix and then solve a linear system Ax =b using scipy, how is this done.

i have tried the following code, which dosent work.


from scipy.sparse import dia_matrix
from scipy.sparse.linalg import spsolve_triangular

N = 10


diag = np.zeros(N) + 2
udiag = np.zeros(N) + 1
A = dia_matrix(([diag, udiag, udiag], [0, 1, -1]), shape=(N, N))


b = np.ones(N)

print(A.todense())
print(b)


x = spsolve_triangular(A, b)

print(x)


Solution

  • The problem comes from the fact that your matrix is not triangular but tridiagonal. As such you have to use the spsolve function instead of the spsolve_triangular function.