0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.linalg.solve in NumPy for Solving Linear Equations

Use np.linalg.solve(A, b) to find the solution vector x for the linear system Ax = b. Here, A is a square matrix of coefficients and b is the right-hand side vector or matrix.
๐Ÿ“

Syntax

The function np.linalg.solve(A, b) solves the linear equation Ax = b where:

  • A: A square 2D numpy array representing coefficients.
  • b: A 1D or 2D numpy array representing the right-hand side values.
  • The output is the solution array x that satisfies the equation.
python
x = np.linalg.solve(A, b)
๐Ÿ’ป

Example

This example solves the system of equations:
2x + 3y = 8
5x + 4y = 13

We represent the coefficients as matrix A and the constants as vector b. Then we use np.linalg.solve to find x and y.

python
import numpy as np

A = np.array([[2, 3], [5, 4]])
b = np.array([8, 13])

x = np.linalg.solve(A, b)
print(x)
Output
[1. 2.]
โš ๏ธ

Common Pitfalls

Common mistakes when using np.linalg.solve include:

  • Passing a non-square matrix A. The matrix must be square (same number of rows and columns).
  • Using a singular matrix A (determinant zero), which has no unique solution.
  • Passing incompatible shapes for b. It must have the same number of rows as A.

Always check matrix shapes and that A is invertible before calling np.linalg.solve.

python
import numpy as np

# Wrong: Non-square matrix A
A_wrong = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([7, 8])

try:
    np.linalg.solve(A_wrong, b)
except np.linalg.LinAlgError as e:
    print(f"Error: {e}")

# Right: Square matrix A
A_right = np.array([[1, 2], [3, 4]])
solution = np.linalg.solve(A_right, np.array([5, 6]))
print(solution)
Output
Error: Last 2 dimensions of the array must be square [-4. 4.5]
๐Ÿ“Š

Quick Reference

  • Input: A (square matrix), b (vector or matrix)
  • Output: Solution vector or matrix x
  • Raises: LinAlgError if A is singular or not square
  • Use case: Solve linear systems efficiently without computing inverse
โœ…

Key Takeaways

Use np.linalg.solve(A, b) to solve Ax = b where A is square and b matches A's rows.
Ensure matrix A is square and invertible to avoid errors.
np.linalg.solve is faster and more accurate than computing the inverse manually.
Check input shapes carefully before calling the function.
Handle exceptions for singular or non-square matrices.