Skip to content

Instantly share code, notes, and snippets.

@j9ac9k
Last active July 9, 2023 01:52
Show Gist options
  • Save j9ac9k/6b5cd12aa9d2e5aa861f942b786293b4 to your computer and use it in GitHub Desktop.
Save j9ac9k/6b5cd12aa9d2e5aa861f942b786293b4 to your computer and use it in GitHub Desktop.
Gaussian Elimination in Python
def gauss(A):
m = len(A)
assert all([len(row) == m + 1 for row in A[1:]]), "Matrix rows have non-uniform length"
n = m + 1
for k in range(m):
pivots = [abs(A[i][k]) for i in range(k, m)]
i_max = pivots.index(max(pivots)) + k
# Check for singular matrix
assert A[i_max][k] != 0, "Matrix is singular!"
# Swap rows
A[k], A[i_max] = A[i_max], A[k]
for i in range(k + 1, m):
f = A[i][k] / A[k][k]
for j in range(k + 1, n):
A[i][j] -= A[k][j] * f
# Fill lower triangular matrix with zeros:
A[i][k] = 0
# Solve equation Ax=b for an upper triangular matrix A
x = []
for i in range(m - 1, -1, -1):
x.insert(0, A[i][m] / A[i][i])
for k in range(i - 1, -1, -1):
A[k][m] -= A[k][i] * x[0]
return x
@j9ac9k
Copy link
Author

j9ac9k commented May 18, 2020

hi , thank you for code but I could not do this which is for 4 or more unknown equations . could you help me ?

Haven't touched this in ages, can you provide a working example? This has handled arbitrary sized equations.

@githubsourav
Copy link

githubsourav commented Jul 4, 2020

def GaussElim(M,V): # Get a Matrix A and Vector B

import numpy as np

A=np.array(M)
B=np.array(V)
Adim=A.shape;   # Dimension of A Matrix
Bdim=B.shape;
print(Adim,Bdim)
NumRow=Adim[0]
NumCol=Adim[1] # How many Number of Rows and Columns
Solve_x=np.zeros((NumRow,1));
# Check for Consistencey of the Solution
if NumRow==NumCol:
   print("Number of Equation is Equal to Number of Variables:- Good \/Checked")  
if Bdim[0]==NumRow:
   print("Size of the Vector is Consistent with Number of Variables:-Good \/Checked")
   # When no solution due to inconsistency  

else:
print("Size of the Vector is Note Correct")
Solve_x="NaN"

b=B.reshape((NumRow,1))    # Reshaping the Vector B into b as a Column vector 
                              # NumPy arrays by default row vector
   # Joining A and b 
CatAB_stack=np.hstack((A,b))  # Horizontally stacking or Concatinating
                              # the M and V
# or Use Numpy Concatenate command as follows 
CatAB_concat=np.concatenate((A,b),axis=1);
#######################################################################
## Forward Elimination
# Getting the size of the new concatenated matrix
R=NumRow;                   # Getting Number of Rows - Redundant NumRow
C=CatAB_stack.shape[1];     # Getting Number of Columns (NumCol+1)
   
CatAB=CatAB_concat;      # Initializig the CatAB - Continuously changing 
                               # Forward Eliminated Matrix 
   
   # range defines like this range(Start Index, Max number of loop, interval)
   
for j in range(NumRow-1):       # for j running from 0 to NumRow-2
  for i in range(j+1, NumRow):   # for i running from j+1 to NumRow
    CatAB[i,j:C]=CatAB[i,j:C]-(CatAB[j,j:C]*(CatAB[i,j]/CatAB[j,j]));
           
   #######################################################################    
   ## Backward Substitution 
    
Solve_x=np.zeros((R,1))     # Initializing the solution vector 
Solve_x[R-1]=CatAB[R-1,C-1]/CatAB[R-1,R-1];  # Solve the last variable -1 to satisfy the index "Matlab-1=C"

# Reverse Looping range(Starting Number,Last Number,- negative increment)
for i in range(NumRow-1,-1,-1):
    var=0
    for j in range(i+1, C-1):
        var+=CatAB[i,j]*Solve_x[j]
        
    Solve_x[i]=(CatAB[i,C-1]-var)/CatAB[i,i]
         
  
return [Solve_x,CatAB] 

@nopeva
Copy link

nopeva commented Jul 28, 2021

hi , thank you for code but I could not do this which is for 4 or more unknown equations . could you help me ?

Haven't touched this in ages, can you provide a working example? This has handled arbitrary sized equations.

Thanks for the code. I am having trouble with singular matrices when using it with bigger matrices and have found the following article which deals with this specific problem for gaussian elimination. It seems to be an easy extension, I wonder if you could give help me with it given I am not familiar with the method: "When a row of zeros, say the ith, is encountered in the transform of A, the diagonal element of that row is changed to 1, and in the augmented portion of the matrix all other rows are changed to 0, the ith row being unchanged".

@fezedimma
Copy link

how would i write a program that does forward elimination - use the naive method for python code

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