Find the column space of a matrix. The column space is the set of all possible linear combinations of the column vectors, represented by the linearly independent columns. Return the basis vectors for the column space.
import numpy as np
def column_space(A):
A = np.array(A, dtype=float)
m, n = A.shape
# Use row echelon form to find pivot columns
mat = A.copy()
pivot_cols = []
row = 0
for col in range(n):
# Find pivot in current column
max_row = row
for r in range(row + 1, m):
if abs(mat[r, col]) > abs(mat[max_row, col]):
max_row = r
if abs(mat[max_row, col]) < 1e-10:
continue
mat[[row, max_row]] = mat[[max_row, row]]
pivot_cols.append(col)
for r in range(row + 1, m):
factor = mat[r, col] / mat[row, col]
mat[r, col:] -= factor * mat[row, col:]
row += 1
# Return original columns at pivot positions
basis = A[:, pivot_cols]
return basis.tolist()