SciPy Linear Algebra
Linear algebra — vectors, matrices and the equations that connect them — sits underneath almost all of scientific computing: fitting models, simulating physics, ranking web pages, compressing images. NumPy has a basic numpy.linalg module; scipy.linalg contains everything in it plus many more routines, and it is always built against the optimised LAPACK and BLAS libraries.
Solving a system of equations
A store sells apples and pears. Three apples and two pears cost 7.40; one apple and four pears cost 8.80. What does each fruit cost? Written as a matrix equation A x = b:
[3 2] [apple] [7.40]
[1 4] [pear ] = [8.80]import numpy as np
from scipy import linalg
A = np.array([[3.0, 2.0],
[1.0, 4.0]])
b = np.array([7.40, 8.80])
x = linalg.solve(A, b)
print(f"apple = {x[0]:.2f}, pear = {x[1]:.2f}")
print("check A @ x:", A @ x)apple = 1.20, pear = 1.90
check A @ x: [7.4 8.8]
Tip: Never compute
inv(A) @ bto solve a system.solve()is faster and more accurate, because it never forms the inverse explicitly.
Determinant, inverse and norms
import numpy as np
from scipy import linalg
A = np.array([[4.0, 7.0],
[2.0, 6.0]])
print("determinant:", round(linalg.det(A), 6))
print("inverse:")
print(np.round(linalg.inv(A), 4))
print("A @ inv(A) is identity:", np.allclose(A @ linalg.inv(A), np.eye(2)))
print("Frobenius norm:", round(linalg.norm(A), 4))
print("1-norm (max column sum):", linalg.norm(A, 1))determinant: 10.0
inverse:
[[ 0.6 -0.7]
[-0.2 0.4]]
A @ inv(A) is identity: True
Frobenius norm: 10.247
1-norm (max column sum): 13.0
A determinant of zero means the matrix is singular: it has no inverse and A x = b has either no solution or infinitely many. SciPy raises LinAlgError in that case:
import numpy as np
from scipy import linalg
singular = np.array([[1.0, 2.0],
[2.0, 4.0]]) # second row = 2 x first row
try:
linalg.solve(singular, [1.0, 2.0])
except linalg.LinAlgError as err:
print("LinAlgError:", err)
print("rank:", np.linalg.matrix_rank(singular))LinAlgError: Matrix is singular.
rank: 1
Telling SciPy about structure
Real matrices often have special structure, and exploiting it can make solving much faster. solve() accepts an assume_a= hint, and there are dedicated solvers:
| Structure | Function / option |
|---|---|
| Symmetric positive definite | solve(A, b, assume_a="pos"), cho_factor + cho_solve |
| Triangular | solve_triangular(A, b, lower=True) |
| Banded (non-zeros near the diagonal) | solve_banded((l, u), ab, b) |
| Toeplitz (constant diagonals) | solve_toeplitz(c, b) |
| Many right-hand sides, same A | lu_factor once, lu_solve many times |
import numpy as np
from scipy import linalg
# A tridiagonal system (common in heat-flow simulations)
n = 6
main = np.full(n, 2.0)
off = np.full(n - 1, -1.0)
A = np.diag(main) + np.diag(off, 1) + np.diag(off, -1)
b = np.ones(n)
# Banded storage: one row per diagonal (upper, main, lower)
ab = np.zeros((3, n))
ab[0, 1:] = off
ab[1, :] = main
ab[2, :-1] = off
x_band = linalg.solve_banded((1, 1), ab, b)
x_full = linalg.solve(A, b)
print("solution:", x_band)
print("same as full solve:", np.allclose(x_band, x_full))solution: [3. 5. 6. 6. 5. 3.]
same as full solve: True
Least squares
When there are more equations than unknowns — for example fitting a straight line through many points — there's usually no exact solution. lstsq() finds the x that minimises the squared error ‖A x − b‖²:
import numpy as np
from scipy import linalg
hours = np.array([1, 2, 3, 4, 5, 6])
score = np.array([52, 55, 61, 64, 70, 71])
# Model: score = slope * hours + intercept -> columns [hours, 1]
A = np.column_stack([hours, np.ones_like(hours)])
coef, residues, rank, sv = linalg.lstsq(A, score)
slope, intercept = coef
print(f"score = {slope:.3f} * hours + {intercept:.3f}")
print(f"predicted for 8 hours: {slope * 8 + intercept:.1f}")score = 4.086 * hours + 47.867
predicted for 8 hours: 80.6
Matrix functions
scipy.linalg can also apply functions like the exponential or square root to a whole matrix (not element by element). The matrix exponential expm is central to solving linear ODE systems:
import numpy as np
from scipy import linalg
# Rotation generator: expm(theta * K) rotates by theta
theta = np.pi / 2
K = np.array([[0.0, -1.0],
[1.0, 0.0]])
R = linalg.expm(theta * K)
print("rotation by 90 degrees:")
print(np.round(R, 6) + 0.0)
print("rotate (1, 0):", np.round(R @ [1, 0], 6) + 0.0)
S = linalg.sqrtm(np.array([[4.0, 0.0], [0.0, 9.0]]))
print("sqrtm diag(4, 9):", np.diag(S))rotation by 90 degrees:
[[ 0. -1.]
[ 1. 0.]]
rotate (1, 0): [0. 1.]
sqrtm diag(4, 9): [2. 3.]
Adding 0.0 after rounding turns any -0. into 0., a small trick for tidy printing.
Test yourself
What is the preferred way to solve A x = b?
- x = inv(A) @ b
- x = linalg.solve(A, b)
- x = b / A
- x = A.T @ b
What does a determinant of 0 tell you about a square matrix?
- It is the identity
- It is singular and has no inverse
- It is symmetric
- It is sparse
Which function finds the best-fit solution when there are more equations than unknowns?
- linalg.det
- linalg.expm
- linalg.lstsq
- linalg.inv