{"record":{"id":"5b6101d87abb6bac","repo":"TheAlgorithms/Python","slug":"matrices-must-have-the-same-dimension","errorCode":null,"errorMessage":"matrices must have the same dimension!","messagePattern":"matrices must have the same dimension!","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/lib.py","lineNumber":317,"sourceCode":"            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\n    def __mul__(self, other: float) -> Matrix: ...\n\n    @overload\n    def __mul__(self, other: Vector) -> Vector: ...\n\n    def __mul__(self, other: float | Vector) -> Vector | Matrix:\n        \"\"\"\n        implements the matrix-vector multiplication.\n        implements the matrix-scalar multiplication\n        \"\"\"\n        if isinstance(other, Vector):  # matrix-vector\n            if len(other) == self.__width:\n                ans = zero_vector(self.__height)\n                for i in range(self.__height):\n                    prods = [\n                        self.__matrix[i][j] * other.component(j)","sourceCodeStart":299,"sourceCodeEnd":335,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/lib.py#L299-L335","documentation":"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).","triggerScenarios":"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.","commonSituations":"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.","solutions":["Assert matching width()/height() before subtracting.","Crop or pad the larger matrix to the shared shape first when the domain permits.","Verify construction arguments (Matrix(data, width, height)) are consistent for both operands.","Catch Exception narrowly around the subtraction."],"exampleFix":"// before\nd = Matrix([[5, 6], [7, 8]], 2, 2) - Matrix([[1, 2, 3]], 3, 1)  # Exception\n\n// after\nassert a.width() == b.width() and a.height() == b.height(), \"shape mismatch\"\nd = a - b","handlingStrategy":"validation","validationCode":"if a.width() != b.width() or a.height() != b.height():\n    raise ValueError(f\"cannot subtract {a.width()}x{a.height()} from {b.width()}x{b.height()}\")\ndiff = a - b","typeGuard":"from linear_algebra.src.lib import Matrix\n\ndef is_matrix_of(obj, width: int, height: int) -> bool:\n    return isinstance(obj, Matrix) and obj.width() == width and obj.height() == height","tryCatchPattern":"try:\n    diff = a - b\nexcept Exception as e:\n    if \"same dimension\" in str(e):\n        raise ValueError(\"matrix shape mismatch in subtraction\") from e\n    raise","preventionTips":["Check width()/height() equality before subtracting matrices from different origins (snapshots, grids, files).","Keep the (data, width, height) constructor arguments consistent across all Matrix creations in a pipeline.","Align/resample grids to a common shape before differencing them.","Prefer validation over catching: the library raises bare Exception, so message-based catching is fragile."],"tags":["linear-algebra","matrix","dimension-mismatch","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}