Skip to content

Instantly share code, notes, and snippets.

@ofan666
Created February 21, 2012 11:11
Show Gist options
  • Save ofan666/1875903 to your computer and use it in GitHub Desktop.
Save ofan666/1875903 to your computer and use it in GitHub Desktop.
Tridiagonal Matrix Algorithm solver in Python, using Numpy array - http://ofan666.blogspot.com/2012/02/tridiagonal-matrix-algorithm-solver-in.html
try:
import numpypy as np # for compatibility with numpy in pypy
except:
import numpy as np # if using numpy in cpython
## Tri Diagonal Matrix Algorithm(a.k.a Thomas algorithm) solver
def TDMAsolver(a, b, c, d):
'''
TDMA solver, a b c d can be NumPy array type or Python list type.
refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
'''
nf = len(a) # number of equations
ac, bc, cc, dc = map(np.array, (a, b, c, d)) # copy the array
for it in xrange(1, nf):
mc = ac[it]/bc[it-1]
bc[it] = bc[it] - mc*cc[it-1]
dc[it] = dc[it] - mc*dc[it-1]
xc = ac
xc[-1] = dc[-1]/bc[-1]
for il in xrange(nf-2, -1, -1):
xc[il] = (dc[il]-cc[il]*xc[il+1])/bc[il]
del bc, cc, dc # delete variables from memory
return xc
@jewettaij
Copy link

jewettaij commented Dec 12, 2019

Could you add a license file to this code?

I agree. I appreciate the code snippet, but I would be happier if there was an explicit license. (I'm using this short code too.) Fortunately, it's one of the easiest methods in linear algebra, so it is easy to rewrite.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment