np.linalg.solve: The Complete Guide

The Linear Algebra module of NumPy offers various methods to apply linear algebra to any numpy array.

np.linalg.solve

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:

  1. Rank, determinant, and trace of an array.
  2. The eigenvalues of matrices
  3. Matrix and vector products (dot, inner, outer, product, etc.), matrix exponentiation.
  4. Solve linear or tensor equations and much more!

Syntax

numpy.linalg.solve(arr1, arr2 )

Parameters

The numpy linalg solve() function takes two main parameters, which are:

  1. arr1: This is array 1, a “Coefficient matrix”.
  2. arr2: This is array 2, an Ordinate or “dependent variable” values matrix.

Return Value

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.

Programming Example

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))

Output

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

Explanation

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.

That’s it.

See also

np.linalg.matrix_power

np.linalg.matrix_rank

np.linalg.svd

np.linalg.qr

np.linalg.cholesky

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.