NumPy Tutorial NumPy Statistics NumPy References

NumPy - linalg.solve() function



The NumPy linalg.solve() function is used to solve a linear matrix equation, or system of linear scalar equations. The syntax for using this function is given below:

Syntax

numpy.linalg.solve(a, b)

Parameters

a Required. Specify the coefficient matrix.
b Required. Specify the ordinate or dependent variable values.

Return Value

Returns solution to the system a x = b. Returned shape is identical to b.

Exception

Raises LinAlgError exception, if a is singular or not square.

Example: Solving system of linear equations

Consider the below mentioned system of linear equations:

System of Linear equations

Which can be represented as below in the matrix form.

Matrix form of System of Linear equations

The solution of the above equations is: x=1, y=5, z=7. This can be solved using numpy.linalg.solve() function as shown in the example below.

import numpy as np
A = np.array([[1, 2, 3], 
              [2, 3, 1],
              [3, 1, 2]])
B = np.array([32, 24, 22])

sol = np.linalg.solve(A, B)
print(sol)

The output of the above code will be:

[ 1.  5.  7.]

❮ NumPy - Functions