Numpy linalg.solve() – Solve a linear matrix equation or system of linear scalar equations

Numpy Linalg Solve Solve A Linear Matrix Equation Or System Of Linear Scalar Equations

Linear equations are one of the most important instruments of modern mathematics.

A linear equation is a mathematical equation represented in the form of a1 x1 + a2 x2 + a3 x3 + . . . . . . .+ an xn + b = 0, where x1, x2 ,x3 ......... xn are variables (or unknowns) and b, a1 , a2 ,a3 are the coefficients which are most of the time real numbers.

A linear equation cannot be defined if the coefficients are all equal to zero.

Hence it is an important parameter of a linear equation. The term “linear” says that the highest power of any variable is equal to unity and not more than that. Linear equations might contain one unknown, or two unknowns (the most common system of linear equations) or ‘n’ number of unknowns.

The standard form of a two-variable linear equation is: ax + by = c where x and y are the unknown variables and a, b and c are the arbitrary, non-zero parameters. In the case of one variable linear equation, it can be written as mx + c = 0.

For each solution that is, for each unique value of the set (x,y) we can plot the values on the cartesian coordinate plane and draw a straight line through them connecting all the points. The graphical representation of a system of linear equations is given below:

Graphical representation of a system of linear equations with two variables.
Graphical representation of a system of linear equations with two variables.

Also read: Numpy linalg.eigvals – Compute the eigenvalues of a general matrix

How to solve linear equations using the matrix method in NumPy?

Matrices can be extremely useful while solving a system of complicated linear equations. A matrix is an i x j rectangular array of numbers, where i is the number of rows and j is the number of columns.

Let us take a simple two-variable system of linear equations and solve it using the matrix method. The system of equations is as follows:

x + 2y = 4
3x − 5y = 1

Now let there be three matrices: A representing the coefficient matrix, B representing the ordinate or dependent matrix, and C, or in some cases for the sake of convention we use X to represent the matrix containing the unknowns. In this case, A, B, and C are defined as follows:

matrix representations.
Matrix representations.

The formula for solving linear equations using the matrix method is as follows:

AC = B 
=> C = A-1 B
here , A-1 = inverse of the matrix A = ( 1/ |A| ) ( adjoint of A) and |A| is the determinant of the matrix A

The determinant of A, |A| = [{(1)(-5) – (3)(2)}] = -11 and the adjoint matrix of A would be:

Adjoint matrix
Adjoint matrix

Hence the inverse of the matrix A that is, A-1 =

Inverse of A
Inverse of A

Now, C, the solution matrix is given by :

Solution matrix.
The solution matrix.

Therefore the value of x = 2 and the value of y= 1 for the given system of linear equation.

Why use NumPy for matrix calculations?

When there is n number of linear equations or when the values of the arbitrary expressions are complicated, this method becomes tedious. Hence we can simply write a program using the Numpy library of python which would take make this process a lot simpler. The Numpy or the numerical python library contains inbuilt functions that help us carry out scientific matrix calculations easily and saves us a lot of time. Let’s look at one of the most important functions for linear equations in the Numpy library namely, Linalg.solve, and how it works.

If you don’t already have Numpy installed on your computer, run the following command in your command prompt to install Numpy, and also make sure you run your command prompt in administrator mode:

pip install numpy

The Numpy linalg.solve function:

The numpy linalg.solve function is a very useful function that takes care of the tedious matrix calculations for you. It is used to solve linear equations and find out the unknown variable or a system of linear scalar equations. It is based on the same condition that we discussed above: AC = B.

Parameters and returns of the function:

  • A : (………N, N): It is an array-like structure that is essentially the coefficient or the arbitrary expressions matrix.
  • B: (……….N, M): Another array-like structure containing the dependent or the ordinate values.

It returns the matrix C or X which contains the values of the unknown variables. The data type of X is ndarray which is equal to the size of the B matrix.

Note: The A matrix should be a square matrix of NxN dimension that is the number of rows= number of columns= N or else the function might raise a LinAlgError.

How to use the numpy linalg.solve function?

The structure of the function is shown below:


The following code is an example of the linalg.solve function where we will use the system of the linear equations from the previous example :

Example 1: Solving a simple predefined system of two linear equations

#import required modules
import numpy as py
#display the system of linear equations
print("the system of equations are:")
print('x + 2y = 4')
print ('AND')
print('3x − 5y = 1')
#form the matrices from the equations
A = py.array ([[1,2],[3,-5]])
#function call nd result calculation
#display the result
print("The solution to the linear equation using matrix method is :")

The above code is a Python script that solves a system of linear equations using the matrix method.

  1. The first step is to import the required module, numpy, and give it an alias “py”.
  2. Next, the code displays the system of linear equations: x + 2y = 4 and 3x – 5y = 1.
  3. The matrices A and B are formed from the equations using the numpy array function. A is a 2×2 matrix formed from the coefficients of the variables in the linear equations, and B is a 1×2 matrix formed from the constant terms in the linear equations.
  4. The code then calls the numpy linear algebra function, solve, and passes A and B as arguments to calculate the solution to the system of linear equations. The result is stored in a variable C.
  5. Finally, the solution to the linear equations is displayed using the print statement. The result shows the values of x and y that satisfy the system of linear equations.

The output should be as follows:

the system of equations are:
x + 2y = 4
3x − 5y = 1
The solution to the linear equation using matrix method is :
[x,y]= [2. 1.]
The code and the output
The code and the output

Example 2: Taking user input for the linear equations

Now we will use user input to solve a system of linear equations using the linalg.solve function. Let’s see how it goes:

#import required modules
import numpy as np
# Taking user input for matrix
Row = int(input("Enter the number of rows for all the matrices:"))
# Initializing the two matrices
A,B = [],[]
#for A  
Col = int(input("Enter the number of columns for A, the coefficient matrix:"))
print("Enter the entries for A row-wise:")

# For user input 1
for i in range(Row): #for loop for row entries
    en =[]
    for j in range(Col):#for loop for column entries

print("the matrix A is =")

#for B
print("since B is a singular matrix we don't need any extra input.")
print("Enter the entries for B row-wise:")
col1= 1 #since B is a singular matrix

# For user input 2
for i in range(Row): #for loop for row entries
    en1 =[]
    for j in range(col1):#for loop for column entries

print("the matrix B is =")

#now calculating the solution
#display the result
print("The solution matrix is [x,y] =", C)

The output should be like the one as follows:

Enter the number of rows for all the matrices:2
Enter the number of columns for A, the coefficient matrix:2
Enter the entries for A row-wise:
the matrix A is =
[[1, 2], [3, -5]]
since B is a singular matrix we don't need any extra input.
Enter the entries for B row-wise:
the matrix B is =
[[4], [1]]
The solution matrix is [x,y] = [[2.]
The code and the output
The code and the output

Also read: Numpy linalg.norm – Matrix or vector norm


The numpy library is a like a gold mine containing precious metals. It has numerous functions that are extremely useful and easy to write on a daily basis. It saves a lot of time and delivers results with extreme precision and accuracy. One such important aspect of the library is the numpy linalg.solve() function . It comes in handy when dealing with complex matrix calculations and lengthy systems of linear equations. For more information on this particular function, visit the official documentation.