DEV Community

Cover image for How to Solve Linear Equations with Matrix Inversion
Deepak Raj
Deepak Raj

Posted on • Originally published at codeperfectplus.com on

4 1 1 1

How to Solve Linear Equations with Matrix Inversion

In this article, we will solve linear equations using inverse matrix using Python and Numpy.

We will solve linear equations using an inverse matrix in two steps. First, we will find the inverse of the matrix and then we will multiply the inverse matrix with the constant matrix.

For this, we will take an example of two linear equations with two variables. we will solve to find the value of x and y.

What is Linear Equation?

A linear equation is an equation of a straight line. It is a polynomial equation of degree 1. A linear equation can have more than one variable.

Standard Form of Linear Equation

The standard form of the linear equation is given below.

ax+by=c ax + by = c

Example of Linear Equation

3x+8y=5 3x + 8y = 5

4x+11y=7 4x + 11y = 7

How to Solve Linear Equations with Matrix Inversion? | Mathematics

A = [[3, 8], 
    [4, 11]]

B = [5, 7]

X = ?


X = inverse(A) . B

Enter fullscreen mode Exit fullscreen mode

How to Find Inverse of Matrix? | Python

Here is the Python code to find the value of x and y using an inverse matrix using Python and Numpy.

""" Solver Linear equation using inverse matrix """
import numpy as np
class LinearEquationSolver(object):
""" Linear Equation solver using inverse matrix
equation: AX = B
X = inverse(A) . B
Args:
A: matrix A (np array)
B: Matrix B (np array)
return:
value of X
"""
def __init__(self, A, B):
self.A = A
self.B = B
def is_valid(self):
"""
check if the correct matrix
# checking if A is square matrix and dot product possible for A and B (n *m )(m*n)
"""
shape_A = self.A.shape
shape_B = self.B.shape
if shape_A[1] == shape_B[0]:
if shape_A[0] == shape_A[1]:
return True
else:
raise Exception("A is not a Square matrix")
else:
raise Exception("Dot Product not possible for A and B")
def inverse_matrix(self, matrix):
""" Inverse the matrix """
try:
inverse_matix = np.linalg.inv(matrix)
return inverse_matix
except Exception as e:
raise ValueError("Inverse of matrix not possible")
def solve(self):
""" main function to solve the equation by calling the dot product between
inverse(A) and B.
"""
coff = 0
if self.is_valid():
inverse_A = self.inverse_matrix(self.A)
coff = np.dot(inverse_A, self.B)
return coff

First, we will check if the matrix is invertible or not. If the matrix is invertible then we will find the inverse of the matrix and then we will multiply the inverse matrix with the constant matrix to find the value of x and y.

Driver Code

It’s time to test our code. Here is the driver code to test our code.

def test_case():
    A = np.array([[3, 8], [4, 11]])
    B = np.array([5, 7])
    solver = LinearEquationSolver(A, B)
    coff = solver.solve()
    print(coff)

if __name__ == " __main__":
    test_case()

Enter fullscreen mode Exit fullscreen mode

Output

[-1. 1.]

Enter fullscreen mode Exit fullscreen mode

Explanation

Here is the explanation of the output.

x=1 x = -1
y=1 y = 1
3x+8y=5 3x + 8y = 5
3(1)+8(1)=5 3(-1) + 8(1) = 5
3+8=5 -3 + 8 = 5
5=5 5 = 5
4x+11y=7 4x + 11y = 7
4(1)+11(1)=7 4(-1) + 11(1) = 7
4+11=7 -4 + 11 = 7
7=7 7 = 7

Conclusion

In this article, we learned how to solve linear equations using an inverse matrix. We learned how to find the inverse of the matrix and how to multiply the inverse matrix with the constant matrix to find the value of x and y.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (2)

Collapse
 
artydev profile image
artydev

Try to solve lights off :-) goobix.com/games/lights-off/

Collapse
 
codeperfectplus profile image
Deepak Raj

Thanks for sharing.
Image description
Interesting game.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up