Skip to content

Instantly share code, notes, and snippets.

@dccxi
Created September 4, 2017 18:32
Show Gist options
  • Save dccxi/38fe23ccbf60c10d35c1cf458351ce22 to your computer and use it in GitHub Desktop.
Save dccxi/38fe23ccbf60c10d35c1cf458351ce22 to your computer and use it in GitHub Desktop.
Pure Python Matrix Inverse
def mtx_inv(M):
I = mtx_idt(len(M))
MI = [M[i]+I[i] for i in xrange(len(M))]
for i in xrange(len(MI)):
if MI[i][i] == 0:
temp = M[i]
M[i] = M[i+1]
M[i+1] = temp
if MI[i][i] != 1:
h = MI[i][i]
for j in xrange(len(MI[0])):
MI[i][j] = Fraction(MI[i][j],h)
for r in xrange(len(MI)):
if r != i:
h = MI[r][i]
for c in xrange(len(MI[0])):
MI[r][c] -= h*MI[i][c]
return [i[-len(M):] for i in MI]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment