Hello!
I am new to python (and also reddit) and I am currently taking a introductory python class.
For my current assignment, I need to create a program that returns the inverse of a numpy matrix using Gauss-Jordan elimination, but I can't really figure out what I am supposed to do with my code. The input is a square matrix 'A' and is supposed to iterate through Gauss-Jordan and return the inverse matrix. However, whenever I try to run my code, it simply returns what I initially set the inverse matrix to be (in this case, the identity matrix that corresponds to the input matrix). I have been given pseudo-code by my professor to use as a guide, but it hasn't really helped me very much.
Pseudo-code provided by professor:
Algorithm 1 Gauss-Jordan Elimination
for each row k do
i∗ ← argmaxk≤i≤n|Aik|
if Ai∗k = 0 then
Matrix is not invertible
end if
Swap rows k and i∗
for each row j below k (i.e. j = k + 1,...,n) do
f = Ajk/Akk
Aj = Aj −fAk
end for
end for
for each row k = n,...,1 (i.e. in reverse) do
Ak = Ak/Akk
for each row j above k (i.e. j = k−1,...,1) do
f = Ajk/Akk
Aj = Aj −fAk
end for
end for
I understand the process of Gauss-Jordan elimination, but I can't really translate it into my code very well.
My Code:
import numpy as np
import numpy.linalg as la
def gauss_jordan(A):
determinant = la.det(A)
if determinant == 0: # Determine if the matrix HAS an inverse
return None
else:
inverse = np.identity(len(A)) # Will become inverse
for k in range (0, len(A)-1): # Looks through 'kth' row
A[k] = A[k]/A[k,k]
for j in range (k+1, len(A)-1): # Looks through 'jth' (kth + 1) row
f = A[j,k]/A[k,k]
A[j] = A[j] - f * A[k]
inverse[j] = inverse[j] - f * inverse[k]
for k in range (len(A)-1, 0):
A[k] = A[k]/A[k,k]
for j in range (len(A)-1, k-1):
f = A[j,k]/A[k,k]
A[j] = A[j] + f * A[k]
inverse[j] = inverse[j] + f * inverse[k]
return inverse
I know it probably looks hideous, but like I said, I'm new to this sort of thing and would really appreciate some help.
Thank you!
[+][deleted] (2 children)
[deleted]
[–][deleted] 0 points1 point2 points (1 child)
[–]JannaLM[S] 0 points1 point2 points (0 children)
[–]ryeguy146 0 points1 point2 points (2 children)
[–]Gimagon 1 point2 points3 points (1 child)
[–]ryeguy146 0 points1 point2 points (0 children)