BUG: Fix matrix_rank crash on empty matrices - #30927
Closed
thakoreh wants to merge 1 commit into
Closed
Conversation
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
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #30915
numpy.linalg.matrix_ranknow correctly handles empty matrices (e.g., shape(0, 3)) by returning 0 instead of raisingValueError.Problem
Previously, calling
matrix_rankon an empty matrix would crash with:This occurred because
S.max()fails on empty arrays.Solution
Added the same
_is_empty_2dguard that other linalg functions (pinv,cond) already use. The rank of an empty matrix is mathematically 0, so we returnzeros(A.shape[:-2], dtype=intp).Testing
Added comprehensive tests for:
All existing tests continue to pass.
Backward Compatibility
✓ No breaking changes - only fixes a crash case
✓ All existing functionality preserved