TheAlgorithms/Python · error · Exception
vector must have the same size as the number of columns of…
Error message
vector must have the same size as the number of columns of the matrix!
What it means
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.
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.
Example fix
// before m = Matrix([[1, 2, 3], [4, 5, 6]], 3, 2) y = m * Vector([1, 2]) # Exception: vector must have the same size ... // after x = Vector([1, 2, 3]) assert len(x) == m.width() y = m * x # returns a 2-dimensional Vector
Defensive patterns
Strategy: validation
Validate before calling
if len(x) != m.width():
raise ValueError(f"vector of size {len(x)} incompatible with {m.height()}x{m.width()} matrix")
y = m * x Type guard
from linear_algebra.src.lib import Matrix, Vector
def is_compatible_vector_for(m: Matrix, v: Vector) -> bool:
return isinstance(v, Vector) and len(v) == m.width() Try / catch
try:
y = m * x
except Exception as e:
if "same size as the number of columns" in str(e):
raise ValueError(f"vector length {len(x)} != matrix width {m.width()}") from e
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- matrices must have the same dimension!
- matrix must have the same dimension!
- must have the same size
- Cannot multiply matrix of dimensions
- change_component: indices out of bounds
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/ce96217fa332b8b0.
Report an issue: GitHub.
Appendix: source
Thrown at linear_algebra/src/lib.py:341
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)
for j in range(self.__width)
]
ans.change_component(i, sum(prods))
return ans
else:
raise Exception(
"vector must have the same size as the "
"number of columns of the matrix!"
)
elif isinstance(other, (int, float)): # matrix-scalar
matrix = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(matrix, self.__width, self.__height)
return None
def height(self) -> int:
"""
getter for the height
"""
return self.__height
def width(self) -> int:View on GitHub (pinned to f5988cc097)