#330 · Linear Algebra · Medium
⊣ Solve on deep-ml.comCompute the null space (kernel) of a matrix A. The null space is the set of all vectors x such that Ax = 0. Return a basis for the null space.
from typing import List
def null_space(matrix: List[List[float]], tol: float = 1e-9) -> List[List[float]]:
if not matrix or not matrix[0]:
return []
m = len(matrix)
n = len(matrix[0])
# Augmented copy for RREF
mat = [row[:] for row in matrix]
pivot_cols = []
row_idx = 0
for col in range(n):
# Find pivot
pivot = -1
for r in range(row_idx, m):
if abs(mat[r][col]) > tol:
pivot = r
break
if pivot == -1:
continue
mat[row_idx], mat[pivot] = mat[pivot], mat[row_idx]
# Scale pivot row
scale = mat[row_idx][col]
for j in range(n):
mat[row_idx][j] /= scale
# Eliminate all other rows
for r in range(m):
if r != row_idx and abs(mat[r][col]) > tol:
factor = mat[r][col]
for j in range(n):
mat[r][j] -= factor * mat[row_idx][j]
pivot_cols.append(col)
row_idx += 1
# Free variables are non-pivot columns
free_cols = [c for c in range(n) if c not in pivot_cols]
basis = []
for fc in free_cols:
vec = [0.0] * n
vec[fc] = 1.0
for i, pc in enumerate(pivot_cols):
vec[pc] = -mat[i][fc]
basis.append(vec)
return basis