Back to Problems

Matrix times Vector (easy)

Write a Python function that takes the dot product of a matrix and a vector. return -1 if the matrix could not be dotted with the vector

Example

Example:
        input: a = [[1,2],[2,4]], b = [1,2]
        output:[5, 10] 
        reasoning: 1*1 + 2*2 = 5;
                   1*2+ 2*4 = 10

Matrix Times Vector

Consider a matrix \(A\) and a vector \(v\), where: Matrix \(A\): \[ A = \begin{pmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{pmatrix} \] Vector \(v\): \[ v = \begin{pmatrix} v_1 \\ v_2 \end{pmatrix} \] The dot product of \(A\) and \(v\) results in a new vector: \[ A \cdot v = \begin{pmatrix} a_{11}v_1 + a_{12}v_2 \\ a_{21}v_1 + a_{22}v_2 \end{pmatrix} \] Things to note: an \(n \times m\) matrix will need to be multiplied by a vector of size \(m\) or else this will not work.
def matrix_dot_vector(a:list[list[int|float]],b:list[int|float])-> list[int|float]:
    if len(a[0]) != len(b):
        return -1
    vals = []
    for i in a:
        hold = 0
        for j in range(len(i)):
            hold+=(i[j] * b[j])
        vals.append(hold)

    return vals

Your Solution

Output will be shown here.