TheAlgorithms/Python · error · Exception

matrices must have the same dimension!

Error message

matrices must have the same dimension!

What it means

Raised by Matrix.__sub__ in linear_algebra/src/lib.py:317, the subtraction counterpart of __add__. If self.__width != other.width() or self.__height != other.height(), component-wise subtraction is undefined and a bare Exception 'matrices must have the same dimension!' is raised (here the message uses the plural 'matrices', unlike the addition case).

Source

Thrown at linear_algebra/src/lib.py:317

            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!")

    @overload
    def __mul__(self, other: float) -> Matrix: ...

    @overload
    def __mul__(self, other: Vector) -> Vector: ...

    def __mul__(self, other: float | Vector) -> Vector | Matrix:
        """
        implements the matrix-vector multiplication.
        implements the matrix-scalar multiplication
        """
        if isinstance(other, Vector):  # matrix-vector
            if len(other) == self.__width:
                ans = zero_vector(self.__height)
                for i in range(self.__height):
                    prods = [
                        self.__matrix[i][j] * other.component(j)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Assert matching width()/height() before subtracting.
  2. Crop or pad the larger matrix to the shared shape first when the domain permits.
  3. Verify construction arguments (Matrix(data, width, height)) are consistent for both operands.
  4. Catch Exception narrowly around the subtraction.

Example fix

// before
d = Matrix([[5, 6], [7, 8]], 2, 2) - Matrix([[1, 2, 3]], 3, 1)  # Exception

// after
assert a.width() == b.width() and a.height() == b.height(), "shape mismatch"
d = a - b
Defensive patterns

Strategy: validation

Validate before calling

if a.width() != b.width() or a.height() != b.height():
    raise ValueError(f"cannot subtract {a.width()}x{a.height()} from {b.width()}x{b.height()}")
diff = a - b

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:
    diff = a - b
except Exception as e:
    if "same dimension" in str(e):
        raise ValueError("matrix shape mismatch in subtraction") from e
    raise

Prevention

When it happens

Trigger: Using - between Matrix objects of different declared dimensions, e.g. subtracting a 3x3 from a 2x2, or subtracting matrices whose width/height constructor arguments disagree with each other even when the raw data is compatible.

Common situations: Computing differences between grids/gradients sampled at different resolutions, image-like data where one operand was cropped or resized, or transposing one operand but not the other.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/5b6101d87abb6bac. Report an issue: GitHub.