TheAlgorithms/Python · error · Exception

vector must have the same size as the number of columns of t

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.

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)

Solutions

  1. Check len(v) == m.width() before the multiplication.
  2. Verify the Matrix constructor's width/height arguments match the data (width = number of columns per row, height = number of rows).
  3. If you meant the transposed action, transpose the data or swap the constructor arguments so width matches the vector length.
  4. 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

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


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