{"record":{"id":"6d25bda38eefe1ca","repo":"TheAlgorithms/Python","slug":"matrix-must-have-the-same-dimension","errorCode":null,"errorMessage":"matrix must have the same dimension!","messagePattern":"matrix must have the same dimension!","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/lib.py","lineNumber":301,"sourceCode":"                else:\n                    ans += str(self.__matrix[i][j]) + \"|\\n\"\n        return ans\n\n    def __add__(self, other: Matrix) -> Matrix:\n        \"\"\"\n        implements matrix addition.\n        \"\"\"\n        if self.__width == other.width() and self.__height == other.height():\n            matrix = []\n            for i in range(self.__height):\n                row = [\n                    self.__matrix[i][j] + other.component(i, j)\n                    for j in range(self.__width)\n                ]\n                matrix.append(row)\n            return Matrix(matrix, self.__width, self.__height)\n        else:\n            raise Exception(\"matrix must have the same dimension!\")\n\n    def __sub__(self, other: Matrix) -> Matrix:\n        \"\"\"\n        implements matrix subtraction.\n        \"\"\"\n        if self.__width == other.width() and self.__height == other.height():\n            matrix = []\n            for i in range(self.__height):\n                row = [\n                    self.__matrix[i][j] - other.component(i, j)\n                    for j in range(self.__width)\n                ]\n                matrix.append(row)\n            return Matrix(matrix, self.__width, self.__height)\n        else:\n            raise Exception(\"matrices must have the same dimension!\")\n\n    @overload","sourceCodeStart":283,"sourceCodeEnd":319,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/lib.py#L283-L319","documentation":"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!'.","triggerScenarios":"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.","commonSituations":"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).","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."],"exampleFix":"// before\nc = Matrix([[1, 2], [3, 4]], 2, 2) + Matrix([[1], [2]], 1, 2)  # Exception\n\n// after\nif (a.width(), a.height()) != (b.width(), b.height()):\n    raise ValueError(f\"shape mismatch: {a.width()}x{a.height()} vs {b.width()}x{b.height()}\")\nc = a + b","handlingStrategy":"validation","validationCode":"def same_shape(a, b) -> bool:\n    return a.width() == b.width() and a.height() == b.height()\n\nif not same_shape(m1, m2):\n    raise ValueError(f\"shape mismatch: {m1.width()}x{m1.height()} vs {m2.width()}x{m2.height()}\")\ns = m1 + m2","typeGuard":"from linear_algebra.src.lib import Matrix\n\ndef is_matrix_of(obj, width: int, height: int) -> bool:\n    return (\n        isinstance(obj, Matrix)\n        and obj.width() == width\n        and obj.height() == height\n    )","tryCatchPattern":"try:\n    s = m1 + m2\nexcept Exception as e:\n    if \"same dimension\" in str(e):\n        raise ValueError(\"cannot add matrices of different dimensions\") from e\n    raise","preventionTips":["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."],"tags":["linear-algebra","matrix","dimension-mismatch","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}