onlyforbopi
9/30/2019 - 5:46 PM

## Python.Math.LinearAlgebra

#python #math #linearalgebra #table #matrix #inverse #determinant

• BasicLinearAlgebra.py : Contains various methods for matrix manipulation.
``````

a = [ [1,0,2,3,4],[1,1,0,2,1],[0,3,1,2,2] ]

def transposeMatrix(m):
return map(list,zip(*m))

def getMatrixMinor(m,i,j):
return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]

def getMatrixDeternminant(m):
#base case for 2x2 matrix
if len(m) == 2:
return m[0][0]*m[1][1]-m[0][1]*m[1][0]

determinant = 0
for c in range(len(m)):
determinant += ((-1)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m,0,c))
return determinant

def getMatrixInverse(m):
determinant = getMatrixDeternminant(m)
#special case for 2x2 matrix:
if len(m) == 2:
return [[m[1][1]/determinant, -1*m[0][1]/determinant],
[-1*m[1][0]/determinant, m[0][0]/determinant]]

#find matrix of cofactors
cofactors = []
for r in range(len(m)):
cofactorRow = []
for c in range(len(m)):
minor = getMatrixMinor(m,r,c)
cofactorRow.append(((-1)**(r+c)) * getMatrixDeternminant(minor))
cofactors.append(cofactorRow)
cofactors = transposeMatrix(cofactors)
for r in range(len(list(cofactors))):
for c in range(len(list(cofactors))):
cofactors[r][c] = cofactors[r][c]/determinant
print(cofactors[r][c])
return cofactors

def LoLto2D(Lol_in):

for j in Lol_in:
for f in j:
print(str(f), end=' ')
print("\n")

LoLto2D(a)
print(list(transposeMatrix(a)))
print(getMatrixMinor(a, 2, 1))
print(getMatrixDeternminant(a))
print(list(getMatrixInverse(a)))``````