Search code examples
pythonnumpytensordot

Batch dot product with numpy?


I need to get the dot product of many vectors with one vector. Example code:

a = np.array([0, 1, 2])

b = np.array([
    [0, 1, 2],
    [4, 5, 6],
    [-1, 0, 1],
    [-3, -2, 1]
])

I would like to get the dot product of each row of b against a. I can iterate:

result = []
for row in b:
    result.append(np.dot(row, a))

print(result)

which gives:

[5, 17, 2, 0]

How can I get this without iterating? Thanks!


Solution

  • Use numpy.dot or numpy.matmul without for loop:

    import numpy as np
    
    np.matmul(b, a)
    # or
    np.dot(b, a)
    

    Output:

    array([ 5, 17,  2,  0])