The Linear Algebra module of NumPy offers various methods to apply linear algebra to any numpy array.
The np.linalg.solve() is a numpy library function that gives the solution of linear equations in the matrix form. The Numpy linalg solve() function is used to solve a linear matrix equation or a system of linear scalar equations.
The solve() function calculates the exact x of the matrix equation ax=b where a and b are given matrices.
Using numpy algebra, one can find:
- Rank, determinant, and trace of an array.
- The eigenvalues of matrices
- Matrix and vector products (dot, inner, outer, product, etc.), matrix exponentiation.
- Solve linear or tensor equations and much more!
numpy.linalg.solve(arr1, arr2 )
The numpy linalg solve() function takes two main parameters, which are:
- arr1: This is array 1, a “Coefficient matrix”.
- arr2: This is array 2, an Ordinate or “dependent variable” values matrix.
The linalg solve() function returns the equation ax=b; the returned type is a matrix with a shape identical to matrix b. This function returns LinAlgError if our first matrix (a) is singular or not square.
Program to show the working of linalg.solve()
# Program to show the working of solve() import numpy as np # creating the array "a" A = np.array([[3, 4, 5], [1, 2, 3], [2, 4, 5]]) B = np.array([9, 8, 7]) print("Array A is: \n", A) print("Array B is : \n", B) # Calculating the equation ans = np.linalg.solve(A, B) # Printing the answer print("Answer of the equation is :\n", ans) # Checking if the answer if correct print(np.allclose(np.dot(A, ans), B))
Array A is: [[3 4 5] [1 2 3] [2 4 5]] Array B is : [9 8 7] Answer of the equation is : [ 2. -10.5 9. ] True
In this example, we have created a 3×3 square matrix, which is not singular, and we have printed that.
Then, we created an array of size 3 and printed that also.
Then, we have called numpy.linalg.solve() to calculate the equation Ax=B. We can see that we have got an output of shape inverse of B.
Also, at last, we checked whether the returned answer was True.