Skip to content

BUG: Fix matrix_rank crash on empty matrices - #30927

Closed
thakoreh wants to merge 1 commit into
numpy:mainfrom
thakoreh:fix/matrix-rank-empty-matrices
Closed

BUG: Fix matrix_rank crash on empty matrices#30927
thakoreh wants to merge 1 commit into
numpy:mainfrom
thakoreh:fix/matrix-rank-empty-matrices

Conversation

@thakoreh

@thakoreh thakoreh commented Mar 4, 2026

Copy link
Copy Markdown

Summary

Fixes #30915

numpy.linalg.matrix_rank now correctly handles empty matrices (e.g., shape (0, 3)) by returning 0 instead of raising ValueError.

Problem

Previously, calling matrix_rank on an empty matrix would crash with:

ValueError: zero-size array to reduction operation maximum which has no identity

This occurred because S.max() fails on empty arrays.

Solution

Added the same _is_empty_2d guard that other linalg functions (pinv, cond) already use. The rank of an empty matrix is mathematically 0, so we return zeros(A.shape[:-2], dtype=intp).

Testing

Added comprehensive tests for:

  • Empty matrices: (0, 3), (3, 0), (0, 0)
  • Stacked empty matrices: (2, 0, 3)
  • Empty matrix with custom tolerance

All existing tests continue to pass.

Backward Compatibility

✓ No breaking changes - only fixes a crash case
✓ All existing functionality preserved

Fixes numpy#30915

numpy.linalg.matrix_rank now correctly handles empty matrices (e.g., shape (0, 3))
by returning 0 instead of raising ValueError.

The rank of an empty matrix is mathematically 0. Other linalg functions (pinv, cond)
already handle this case via the _is_empty_2d guard - this adds the same check to matrix_rank.

Changes:
- Add _is_empty_2d check in matrix_rank to return zeros for empty matrices
- Add comprehensive tests for empty matrix cases (0xN, Mx0, 0x0, stacked)
- Maintains backward compatibility for all existing use cases
@seberg

seberg commented Mar 4, 2026

Copy link
Copy Markdown
Member

Please compare with the PR in #30422 which solved most of this, but missed a branch.

And on a general note that we should just ask always: We would prefer to know about any (AI) tool use. We haven't spelled things out, but a "sprintable" label is also to learn and e.g. fully automated PRs to solve them could also be triggered by maintainers.

@thakoreh thakoreh closed this Mar 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3 participants