Skip to content

fix: correct matrix size validation and handle rectangular matrix operations - #15604

Open
hardikkaurani wants to merge 1 commit into
TheAlgorithms:masterfrom
hardikkaurani:fix/matrix-operation-dimensions
Open

hardikkaurani wants to merge 1 commit into
TheAlgorithms:masterfrom
hardikkaurani:fix/matrix-operation-dimensions

Conversation

@hardikkaurani

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Problem & Context

  1. Index error in _verify_matrix_sizes:
    In matrix/matrix_operation.py, _shape(matrix_a) + _shape(matrix_b) produces (rows_a, cols_a, rows_b, cols_b). The condition shape[0] != shape[3] or shape[1] != shape[2] inadvertently compared rows_a with cols_b and cols_a with rows_b. This caused valid addition and subtraction of identical rectangular (non-square) matrices (e.g., add([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]])) to erroneously raise ValueError: operands could not be broadcast together with shape ((2, 3)), ((2, 3)).
  2. Dimension check & UnboundLocalError in multiply():
    In multiply(), calling _verify_matrix_sizes was incorrect because matrix multiplication does not require operands to have identical shapes; it requires inner dimensions to match (cols_a == rows_b). Calling _verify_matrix_sizes rejected valid multiplications where rows_a != cols_b (e.g. multiplying a 2x3 matrix with a 3x4 matrix). Furthermore, passing non-matrix inputs caused an UnboundLocalError on cols instead of raising TypeError("Expected a matrix, got int/list instead") like add() and subtract().
  3. ty warning on redundant condition in subtract():
    Calling and _verify_matrix_sizes(matrix_a, matrix_b) inside the if condition triggered ty's warning[redundant-condition]: A 2-element tuple is always truthy.

Changes Made

  • In _verify_matrix_sizes(), corrected the condition to shape[0] != shape[2] or shape[1] != shape[3].
  • In subtract(), invoked _verify_matrix_sizes(matrix_a, matrix_b) as a statement, matching add().
  • In multiply(), compared inner dimensions cols_a == rows_b directly and raised TypeError when inputs are not matrices.
  • Added doctests covering rectangular matrix addition, subtraction, and multiplication.
  • Updated matrix/tests/test_matrix_operation.py to test rectangular matrices and corrected copy-pasted helper calls (matop.add -> matop.multiply in test_multiplication).

Verification

  • uvx --with numpy pytest matrix/tests/test_matrix_operation.py matrix/matrix_operation.py --doctest-modules: 33 passed.
  • uvx ty check matrix/matrix_operation.py: All checks passed (0 diagnostics, 0 warnings).
  • uvx ruff check matrix/matrix_operation.py matrix/tests/test_matrix_operation.py: All checks passed.
  • uvx ruff format --check matrix/matrix_operation.py matrix/tests/test_matrix_operation.py: Clean.

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.

…rations

- Fix index transposition in _verify_matrix_sizes where rows_a was compared with cols_b and cols_a with rows_b, which incorrectly raised ValueError on valid rectangular matrix addition and subtraction.
- In multiply(), compare inner dimensions cols_a == rows_b directly instead of calling _verify_matrix_sizes, allowing rectangular matrix multiplication with distinct outer dimensions (e.g., 2x3 by 3x4).
- In multiply(), raise TypeError instead of causing an UnboundLocalError when invalid non-matrix inputs are passed.
- In subtract(), call _verify_matrix_sizes as a statement to eliminate ty warning[redundant-condition] on truthiness of a 2-element tuple.
- Update matrix/tests/test_matrix_operation.py to test rectangular matrix addition, subtraction, multiplication, and fix copy-paste calls in test_multiplication and test_subtraction.
Copilot AI balanced review requested due to automatic review settings October 19, 2026 11:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@hardikkaurani

Copy link
Copy Markdown
Author

Hi @cclauss,

I've submitted this pull request to fix an index transposition in _verify_matrix_sizes() and correct the dimension checks in matrix/matrix_operation.py.

Quick overview of the fixes:

  1. Rectangular matrix addition and subtraction:
    _shape(matrix_a) + _shape(matrix_b) produces (rows_a, cols_a, rows_b, cols_b). The check shape[0] != shape[3] or shape[1] != shape[2] inadvertently compared rows_a with cols_b and cols_a with rows_b, which caused valid addition and subtraction of identical rectangular matrices (such as two 2x3 matrices) to fail with ValueError. This is now corrected to shape[0] != shape[2] or shape[1] != shape[3].
  2. Matrix multiplication dimension check & input handling:
    multiply() previously called _verify_matrix_sizes, which erroneously prevented multiplying matrices with distinct outer dimensions (e.g., 2x3 by 3x4). This now verifies inner dimensions cols_a == rows_b directly. In addition, passing invalid inputs to multiply() now raises TypeError consistently instead of raising an UnboundLocalError.
  3. ty clean:
    Calling _verify_matrix_sizes as a statement in subtract() eliminates ty's warning[redundant-condition]: A 2-element tuple is always truthy.
  4. Testing:
    Added doctests and updated matrix/tests/test_matrix_operation.py with rectangular test cases and fixed the test helper calls.

All 33 unit tests and doctests pass (uvx --with numpy pytest matrix/tests/test_matrix_operation.py matrix/matrix_operation.py --doctest-modules), ty check matrix/matrix_operation.py passes with 0 diagnostics, and ruff check/ruff format are completely clean.

Whenever you have a chance, could you please take a look? Thank you!

@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Oct 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants