AppDividend
Latest Code Tutorials

# Numpy linalg solve() Function in Python Example

Numpy linalg solve() function is used to solve a linear matrix equation or a system of linear scalar equation. The solve() function calculates the exact x of the matrix equation ax=b where a and b are given matrices.

## Numpy linalg solve()

The numpy.linalg.solve() function gives the solution of linear equations in the matrix form.

The Linear Algebra module of NumPy offers various methods to apply linear algebra on any numpy array.
One can find:

1. Rank, determinant, trace, etc. 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, which is a “Coefficient matrix”.
2. arr2: This is array 2, which is 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 the 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 have 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 have checked if the returned answer is True or not.

## See also

Numpy linalg matrix_power()

Numpy linalg matrix_rank()

Numpy linalg svd()

Numpy linalg qr()

Numpy linalg cholesky()

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