TheAlgorithms/Python · error · ValueError
Invalid matrix dimensions
Error message
Invalid matrix dimensions
What it means
Raised by matrix_multiply_recursive when either input matrix is not square, or the two matrices do not have the same dimension. This recursive block-multiplication implementation only supports equal-sized square matrices (it splits matrices into quadrants), which is far stricter than general matrix multiplication. Empty matrices short-circuit to [] instead.
Source
Thrown at matrix/matrix_multiplication_recursion.py:113
>>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_wide)
Traceback (most recent call last):
...
ValueError: Invalid matrix dimensions
>>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_high)
Traceback (most recent call last):
...
ValueError: Invalid matrix dimensions
>>> matrix_multiply_recursive(matrix_1_to_4, matrix_count_up)
Traceback (most recent call last):
...
ValueError: Invalid matrix dimensions
"""
if not matrix_a or not matrix_b:
return []
if not all(
(len(matrix_a) == len(matrix_b), is_square(matrix_a), is_square(matrix_b))
):
raise ValueError("Invalid matrix dimensions")
# Initialize the result matrix with zeros
result = [[0] * len(matrix_b[0]) for _ in range(len(matrix_a))]
# Recursive multiplication of matrices
def multiply(
i_loop: int,
j_loop: int,
k_loop: int,
matrix_a: Matrix,
matrix_b: Matrix,
result: Matrix,
) -> None:
"""
:param matrix_a: A square Matrix.
:param matrix_b: Another square Matrix with the same dimensions as matrix_a.
:param result: Result matrix
:param i: Index used for iteration during multiplication.View on GitHub (pinned to f5988cc097)
Solutions
- Pre-check with the module's is_square() helper on both matrices and len equality before calling.
- If your matrices are rectangular but compatible (cols_a == rows_b), use the general algorithm in matrix_operation.multiply or matrix_class.Matrix.__mul__ instead.
- Pad rectangular matrices to square with zero rows/columns if the algorithm's constraint is acceptable for your use case, then trim the result.
- Rename expectations in tests: this function's contract is same-size square matrices only.
Example fix
# before result = matrix_multiply_recursive(a_2x3, b_3x3) # ValueError # after from matrix.matrix_operation import multiply result = multiply(a_2x3, b_3x3) # general multiplication
Defensive patterns
Strategy: validation
Validate before calling
from matrix.matrix_multiplication_recursion import is_square
if not matrix_a or not matrix_b:
result = []
elif len(matrix_a) != len(matrix_b) or not is_square(matrix_a) or not is_square(matrix_b):
raise ValueError("recursive multiply requires two equal-size square matrices")
else:
result = matrix_multiply_recursive(matrix_a, matrix_b) Type guard
def is_uniform_square_pair(a: list, b: list) -> bool:
"""Guard: both non-empty square nested lists of the same dimension."""
return (
bool(a) and bool(b)
and isinstance(a, list) and isinstance(b, list)
and len(a) == len(b)
and all(len(r) == len(a) for r in a)
and all(len(r) == len(b) for r in b)
) Try / catch
try:
result = matrix_multiply_recursive(a, b)
except ValueError as e:
if "Invalid matrix dimensions" in str(e):
from matrix.matrix_operation import multiply
result = multiply(a, b) # general algorithm handles compatible rectangles
else:
raise Prevention
- Reserve this function for equal-size square matrices; use the general multiply for everything else.
- Pre-check with the module's own is_square() helper rather than reimplementing shape logic.
- Pad rectangular matrices with zero rows/columns only if trimming the result is acceptable in your domain.
When it happens
Trigger: matrix_multiply_recursive([[1, 2], [3, 4]], [[1, 2, 3], [4, 5, 6]]) (second not square), or multiplying a 2x2 by a 3x3. Any non-square operand or size mismatch between two square operands triggers it.
Common situations: Assuming this helper is a general multiplier because of its name; feeding rectangular data matrices from a dataset; porting code from NumPy dot() which handles any compatible shapes.
Related errors
- Only square matrices can be raised to a power
- Matrix is not square
- double_factorial_recursive() only accepts integral values
- double_factorial_recursive() not defined for negative values
- power is negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/f0fa6bb0a91c9828.
Report an issue: GitHub.