🌐 AI搜索 & 代理 主页
Skip to content

Conversation

@CodeLoopdroid
Copy link

This PR fixes a bug in np.linalg.matrix_rank where empty matrices
(previously with 0 rows or 0 columns) would raise a ValueError due to
attempting a reduction operation on a zero-size array.

Changes include:

  • Return 0 for all empty matrices in matrix_rank.
  • Added tests covering all empty matrix shapes to ensure the correct behavior.

Files modified:

  • numpy/linalg/_linalg.py
  • numpy/linalg/tests/test_linalg.py

Closes #30421

Fix trailing whitespace causing lint failure and simplify the empty-matrix
rank assertion.

# Handle empty matrices - rank is 0 for matrices with 0 rows or 0 columns
if A.size == 0:
return 0
Copy link
Member

@seberg seberg Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should just add initial=0 which I assume also works. The tests you added are missing the case of np.zeros((0, 5, 5)) where this return is clearly incorrect.

EDIT: Actually, while we are here, can you check if we don't return np.intp(0) on the last return? We may want to adjust the return type for the other early return as well.

@CodeLoopdroid CodeLoopdroid requested a review from seberg December 12, 2025 11:12
@seberg seberg removed their request for review December 12, 2025 11:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: np.linalg.matrix_rank fails for empty matrices

2 participants