Search code examples
pythonnumpynumpy-ndarrayarray-broadcasting

How to do dot product of a vector with a set of vectors in an array using numpy?


Given a N by M array W and a vector V of size N, how do I take the dot product V with every column of W, resulting in a 1-D array D of size M with each element of D consisting out of the dot product of V and W[:,i].

So something like

V = np.random.int(N)
W = np.random.int((N,M))
D = np.zeros(M)
for i in np.arange(M):
    D[i] = dotproduct(V,W[:,i])

Is there a way to do this using just numpy arrays and numpy functions? I want to avoid using for loops.


Solution

  • Use np.dot()

    v = np.random.randint(3,size = 3)
    w =np.random.randint(9, size = (3,3))
    np.dot(v,w)