Lesson 18 of 18
Matrix Rank
Matrix Rank
The rank of a matrix is the number of linearly independent rows (or equivalently, columns). It tells you:
- How many equations in are truly independent
- The dimension of the column space (image) and row space
- Whether is invertible (full rank iff for square )
Key Facts
| Condition | Rank |
|---|---|
| All rows independent | (full row rank) |
| All columns independent | (full column rank) |
| Zero matrix | |
| Redundant rows/columns |
Computing Rank via Row Reduction
Row operations don't change the rank. Reduce to row-echelon form and count non-zero pivot rows:
Row 3 became all zeros — it was a linear combination of rows 1 and 2.
Algorithm
def matrix_rank(A):
m = [row[:] for row in A]
rows, cols = len(m), len(m[0])
rank = 0
for col in range(cols):
# find pivot in this column at or below current rank
pivot = next((r for r in range(rank, rows)
if abs(m[r][col]) > 1e-10), -1)
if pivot == -1:
continue
m[rank], m[pivot] = m[pivot], m[rank]
s = m[rank][col]
m[rank] = [x/s for x in m[rank]]
for r in range(rows):
if r != rank and abs(m[r][col]) > 1e-10:
f = m[r][col]
m[r] = [m[r][j] - f*m[rank][j] for j in range(cols)]
rank += 1
return rank
Your Task
Implement matrix_rank(A) by Gaussian elimination, counting the pivot rows.
Pyodide loading...
Loading...
Click "Run" to execute your code.