{"record":{"id":"ce96217fa332b8b0","repo":"TheAlgorithms/Python","slug":"vector-must-have-the-same-size-as-the-number-of-co","errorCode":null,"errorMessage":"vector must have the same size as the number of columns of the matrix!","messagePattern":"vector must have the same size as the number of columns of the matrix!","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/lib.py","lineNumber":341,"sourceCode":"    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)\n                        for j in range(self.__width)\n                    ]\n                    ans.change_component(i, sum(prods))\n                return ans\n            else:\n                raise Exception(\n                    \"vector must have the same size as the \"\n                    \"number of columns of the matrix!\"\n                )\n        elif isinstance(other, (int, float)):  # matrix-scalar\n            matrix = [\n                [self.__matrix[i][j] * other for j in range(self.__width)]\n                for i in range(self.__height)\n            ]\n            return Matrix(matrix, self.__width, self.__height)\n        return None\n\n    def height(self) -> int:\n        \"\"\"\n        getter for the height\n        \"\"\"\n        return self.__height\n\n    def width(self) -> int:","sourceCodeStart":323,"sourceCodeEnd":359,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/lib.py#L323-L359","documentation":"Raised by Matrix.__mul__ in linear_algebra/src/lib.py:341 on the matrix-vector path: when multiplying a Matrix by a Vector whose length does not equal the matrix's width (number of columns), the per-row dot products over range(self.__width) would read past the vector, so the implementation raises a bare Exception instead. Note the requirement is len(vector) == width, not height — an m x n matrix needs an n-dimensional vector and returns an m-dimensional one.","triggerScenarios":"Calling Matrix(2x3_data, 3, 2) * Vector([1, 2]) — a 3-column matrix times a 2-dimensional vector. Also confusing rows with columns: multiplying by a vector of length height() instead of width() on a non-square matrix.","commonSituations":"Applying a transformation matrix built with dimensions swapped (the constructor takes (data, width, height) — easy to flip), or transforming feature vectors whose dimensionality changed between model versions.","solutions":["Check len(v) == m.width() before the multiplication.","Verify the Matrix constructor's width/height arguments match the data (width = number of columns per row, height = number of rows).","If you meant the transposed action, transpose the data or swap the constructor arguments so width matches the vector length.","Catch Exception narrowly around the multiplication."],"exampleFix":"// before\nm = Matrix([[1, 2, 3], [4, 5, 6]], 3, 2)\ny = m * Vector([1, 2])  # Exception: vector must have the same size ...\n\n// after\nx = Vector([1, 2, 3])\nassert len(x) == m.width()\ny = m * x  # returns a 2-dimensional Vector","handlingStrategy":"validation","validationCode":"if len(x) != m.width():\n    raise ValueError(f\"vector of size {len(x)} incompatible with {m.height()}x{m.width()} matrix\")\ny = m * x","typeGuard":"from linear_algebra.src.lib import Matrix, Vector\n\ndef is_compatible_vector_for(m: Matrix, v: Vector) -> bool:\n    return isinstance(v, Vector) and len(v) == m.width()","tryCatchPattern":"try:\n    y = m * x\nexcept Exception as e:\n    if \"same size as the number of columns\" in str(e):\n        raise ValueError(f\"vector length {len(x)} != matrix width {m.width()}\") from e\n    raise","preventionTips":["Remember the rule: len(vector) must equal the matrix's WIDTH (columns); the result has the matrix's HEIGHT (rows).","Verify Matrix(data, width, height) arguments against the data — swapped dimensions are the most common cause on square-looking data.","Note the m x n matrix needs an n-vector; if you have an m-vector you probably need the transpose.","Also note __mul__ returns None (not an error) for unsupported operand types — check the result type when operands are dynamic."],"tags":["linear-algebra","matrix","vector","dimension-mismatch","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}