← back

Matrix-Vector Dot Product

#1 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Given a matrix (list of lists) and a vector (list), compute the dot product of the matrix and vector. If the number of columns in the matrix does not equal the length of the vector, return -1.

Solution

1
2
3
4
def matrix_dot_vector(a: list[list[int|float]], b: list[int|float]) -> list[int|float]:
    if len(a[0]) != len(b):
        return -1
    return [sum(row[i] * b[i] for i in range(len(b))) for row in a]

Explanation

  1. First validate that the matrix column count matches the vector length.
  2. For each row in the matrix, compute the sum of element-wise products between that row and the vector.
  3. Collect each row's dot product into the result list.

Complexity

  • Time: O(m * n) where m is the number of rows and n is the number of columns
  • Space: O(m) for the output vector