Skip to content

Linear Algebra with NumPy

Linear algebra appears in:

  • Regression
  • Optimization
  • Dimensionality reduction
  • Correlation and covariance

NumPy provides numpy.linalg for common operations like decompositions, inverses, and determinants.

dot
import numpy as np
 
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
 
print(np.dot(a, b))  # 1*4 + 2*5 + 3*6

* on two 2D arrays is element-wise. Matrix multiplication needs @ or np.matmul (equivalently np.dot for 2D arrays).

matmul
import numpy as np
 
A = np.array([[1, 2], [3, 4]])
B = np.array([[10, 20], [30, 40]])
 
print(A @ B)
print(np.matmul(A, B))
diagram Linear algebra toolbox mermaid
numpy.linalg covers the standard matrix operations you need for regression, PCA, and solving systems.
transpose
import numpy as np
 
A = np.array([[1, 2], [3, 4]])
print(A.T)
det-inv
import numpy as np
 
A = np.array([[1, 2], [3, 4]])
 
det = np.linalg.det(A)
inv = np.linalg.inv(A)
 
print("det:", det)
print("inv:\n", inv)

Solving A x = b directly with np.linalg.solve is faster and more numerically stable than computing inv(A) @ b.

solve
import numpy as np
 
A = np.array([[2, 1], [1, 3]])
b = np.array([8, 13])
 
x = np.linalg.solve(A, b)
print(x)
eig
import numpy as np
 
A = np.array([[2, 0], [0, 3]])
vals, vecs = np.linalg.eig(A)
 
print("eigenvalues:", vals)
print("eigenvectors:\n", vecs)
norm
import numpy as np
 
v = np.array([3, 4])
print(np.linalg.norm(v))  # 5

Continue to: Statistical Functions in NumPy for mean/median/std/percentiles and basic descriptive analytics.

Exercise 2 – Matrix Multiplication with @

Section titled “Exercise 2 – Matrix Multiplication with @”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading