TheAlgorithms/Python · error · ValueError

Subtraction requires matrices of the same order

Error message

Subtraction requires matrices of the same order

What it means

Error "Subtraction requires matrices of the same order" thrown in TheAlgorithms/Python.

Source

Thrown at matrix/matrix_class.py:310

    def __ne__(self, other: object) -> bool:
        return not self == other

    def __neg__(self) -> Matrix:
        return self * -1

    def __add__(self, other: Matrix) -> Matrix:
        if self.order != other.order:
            raise ValueError("Addition requires matrices of the same order")
        return Matrix(
            [
                [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)]
                for i in range(self.num_rows)
            ]
        )

    def __sub__(self, other: Matrix) -> Matrix:
        if self.order != other.order:
            raise ValueError("Subtraction requires matrices of the same order")
        return Matrix(
            [
                [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)]
                for i in range(self.num_rows)
            ]
        )

    def __mul__(self, other: Matrix | float) -> Matrix:
        if isinstance(other, (int, float)):
            return Matrix(
                [[int(element * other) for element in row] for row in self.rows]
            )
        elif isinstance(other, Matrix):
            if self.num_columns != other.num_rows:
                raise ValueError(
                    "The number of columns in the first matrix must "
                    "be equal to the number of rows in the second"
                )

View on GitHub (pinned to f5988cc097)

Solutions

  1. Subtract only matrices with identical dimensions.

When it happens

Trigger: Thrown at matrix/matrix_class.py:310 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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