Python Program to Inverse Matrix Using Gauss Jordan
To inverse square matrix of order n using Gauss Jordan Elimination, we first augment input matrix of size n x n by Identity Matrix of size n x n.
After augmentation, row operation is carried out according to Gauss Jordan Elimination to transform first n x n part of n x 2n augmented matrix to identity matrix.
Matrix Inverse Using Gauss Jordan Python Program
# Importing NumPy Library
import numpy as np
import sys
# Reading order of matrix
n = int(input('Enter order of matrix: '))
# Making numpy array of n x 2n size and initializing
# to zero for storing augmented matrix
a = np.zeros((n,2*n))
# Reading matrix coefficients
print('Enter Matrix Coefficients:')
for i in range(n):
for j in range(n):
a[i][j] = float(input( 'a['+str(i)+']['+ str(j)+']='))
# Augmenting Identity Matrix of Order n
for i in range(n):
for j in range(n):
if i == j:
a[i][j+n] = 1
# Applying Guass Jordan Elimination
for i in range(n):
if a[i][i] == 0.0:
sys.exit('Divide by zero detected!')
for j in range(n):
if i != j:
ratio = a[j][i]/a[i][i]
for k in range(2*n):
a[j][k] = a[j][k] - ratio * a[i][k]
# Row operation to make principal diagonal element to 1
for i in range(n):
divisor = a[i][i]
for j in range(2*n):
a[i][j] = a[i][j]/divisor
# Displaying Inverse Matrix
print('\nINVERSE MATRIX IS:')
for i in range(n):
for j in range(n, 2*n):
print(a[i][j], end='\t')
print()
Output
Enter order of matrix: 3 Enter Matrix Coefficients: a[0][0]=1 a[0][1]=1 a[0][2]=3 a[1][0]=1 a[1][1]=3 a[1][2]=-3 a[2][0]=-2 a[2][1]=-4 a[2][2]=-4 INVERSE MATRIX IS: 3.0 1.0 1.5 -1.25 -0.25 -0.75 -0.25 -0.25 -0.25
Recommended Readings