Batch dot product with numpy?

Question:

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!

Asked By: alliedtoasters

||

Answers:

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])
Answered By: Chris

I will just do @

b@a
Out[108]: array([ 5, 17,  2,  0])
Answered By: BENY

can be useful if you need to line by line multiply two arrays of vectors

np.sum(a * b, axis=1)

Answered By: Alexander Nikolaev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.