Skip to content
NumPy

Linear Algebra

Solve systems, factorize, and compute eigenvalues.

By EZ4Code Team
linalgmatrix

Code

import numpy as np

A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])

# Solve linear system Ax = b
x = np.linalg.solve(A, b)
print(x)

# Matrix products and inverse
M = np.array([[1, 2], [3, 4]])
print(M @ M.T)
print(np.linalg.inv(M))

# Determinant, rank, eigenvalues
print(np.linalg.det(M), np.linalg.matrix_rank(M))
eigvals, eigvecs = np.linalg.eig(M)
print(eigvals)

# Least squares
coef, *_ = np.linalg.lstsq(np.vstack([np.ones(5), np.arange(5)]).T,
                           np.array([1, 3, 2, 5, 4]), rcond=None)

Explanation

np.linalg.solve finds x in Ax = b more stably and quickly than computing an inverse. The @ operator performs matrix multiplication, and inv, det, rank, and eig cover standard decompositions. lstsq returns the best-fit coefficients for an overdetermined linear system.

More NumPy Snippets