TheAlgorithms/Python · error · Exception
matrix must have the same dimension!
Error message
matrix must have the same dimension!
What it means
Raised by Matrix.__add__ in linear_algebra/src/lib.py:301 when adding two Matrix objects whose width() and/or height() differ. Matrix addition is component-wise, so both operands must share identical dimensions; on mismatch a bare Exception is thrown with the (slightly misleading singular) message 'matrix must have the same dimension!'.
Source
Thrown at linear_algebra/src/lib.py:301
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def __add__(self, other: Matrix) -> Matrix:
"""
implements matrix addition.
"""
if self.__width == other.width() and self.__height == other.height():
matrix = []
for i in range(self.__height):
row = [
self.__matrix[i][j] + other.component(i, j)
for j in range(self.__width)
]
matrix.append(row)
return Matrix(matrix, self.__width, self.__height)
else:
raise Exception("matrix must have the same dimension!")
def __sub__(self, other: Matrix) -> Matrix:
"""
implements matrix subtraction.
"""
if self.__width == other.width() and self.__height == other.height():
matrix = []
for i in range(self.__height):
row = [
self.__matrix[i][j] - other.component(i, j)
for j in range(self.__width)
]
matrix.append(row)
return Matrix(matrix, self.__width, self.__height)
else:
raise Exception("matrices must have the same dimension!")
@overloadView on GitHub (pinned to f5988cc097)
Solutions
- Compare a.width() == b.width() and a.height() == b.height() before the + operation.
- Verify the (width, height) constructor arguments match the actual nested-list dimensions at every construction site.
- Pad the smaller matrix with zero rows/columns if the domain allows.
- Catch Exception narrowly around the addition at trust boundaries.
Example fix
// before
c = Matrix([[1, 2], [3, 4]], 2, 2) + Matrix([[1], [2]], 1, 2) # Exception
// after
if (a.width(), a.height()) != (b.width(), b.height()):
raise ValueError(f"shape mismatch: {a.width()}x{a.height()} vs {b.width()}x{b.height()}")
c = a + b Defensive patterns
Strategy: validation
Validate before calling
def same_shape(a, b) -> bool:
return a.width() == b.width() and a.height() == b.height()
if not same_shape(m1, m2):
raise ValueError(f"shape mismatch: {m1.width()}x{m1.height()} vs {m2.width()}x{m2.height()}")
s = m1 + m2 Type guard
from linear_algebra.src.lib import Matrix
def is_matrix_of(obj, width: int, height: int) -> bool:
return (
isinstance(obj, Matrix)
and obj.width() == width
and obj.height() == height
) Try / catch
try:
s = m1 + m2
except Exception as e:
if "same dimension" in str(e):
raise ValueError("cannot add matrices of different dimensions") from e
raise Prevention
- Compare width()/height() before every cross-source Matrix addition.
- Double-check Matrix(data, width, height) constructor arguments — the order is width then height, and swapping them makes compatible data look incompatible.
- Validate nested-list dimensions at load time (every row same length, matching declared width).
- Pad smaller matrices with zero rows/columns in the data layer if mixed sizes are legitimate.
When it happens
Trigger: Using + between Matrix instances constructed with different (width, height) arguments, e.g. Matrix(m1, 2, 2) + Matrix(m2, 2, 3). The check is on the stored __width/__height fields, so even mathematically same-shaped raw data raises if the declared dimensions differ.
Common situations: Matrices loaded from different data sources with different column counts, a copy/edit that changed one operand's shape, or constructing Matrix with the width/height arguments swapped (Matrix(data, 3, 2) vs Matrix(data, 2, 3)) — note the constructor signature is (matrix, width, height).
Related errors
- matrices must have the same dimension!
- vector must have the same size as the number of columns of t
- determinant modular {req_l} of encryption key({det}) is not
- 'table' has to be of square shaped array but got a {rows}x{c
- must have the same size
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/6d25bda38eefe1ca.
Report an issue: GitHub.