ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

NumPy Tutorial• 7 min read

Linear Algebra & Matrix Multiplication (np.linalg)

Dot products, the @ operator, matrix inverse, determinants, and eigenvalues

The np.linalg module provides high-performance BLAS/LAPACK implementations for matrix products, inversions, eigenvalues, and linear equation solvers.

Matrix Multiplication with the @ Operator

Element-wise multiplication uses *: A * B multiplies matching positions.

Matrix dot product uses the @ infix operator (Python 3.5+) or np.matmul(A, B). For shapes (m, k) @ (k, n), inner dimensions must match, yielding (m, n).

Matrix Inversion: np.linalg.inv(A) calculates the inverse such that A @ inv(A) = I.

Solving Linear Systems: np.linalg.solve(A, b) solves Ax = b directly without computing explicit matrix inversion, providing superior numerical stability.

Solving Systems of Linear Equations
import numpy as np

# System of equations:
# 2x + 3y = 8
# 4x + 9y = 20
A = np.array([[2, 3], [4, 9]], dtype=np.float64)
b = np.array([8, 20], dtype=np.float64)

# Solve for [x, y]
x, y = np.linalg.solve(A, b)
print(f"Solution: x = {x:.2f}, y = {y:.2f}")

# Verify: A @ [x, y] should equal b
print("Verification (A @ solution):", A @ np.array([x, y]))
np.linalg.solve uses LU factorization for high speed and numerical precision.
Pro Tip

Never compute inv(A) @ b to solve linear systems. Always use np.linalg.solve(A, b), which is both faster and far less prone to floating-point rounding degradation.

ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which operator was added in Python 3.5 specifically for NumPy matrix multiplication?