AP730
AP730

Reputation: 43

Matrix multiplication with multiple numpy arrays

What is the quickest way to multiply a matrix against a numpy array of vectors? I need to multiply a matrix A by every single vector in a list of 1000 vectors. Using a for loop is taking too long, so I was wondering if there's a way to multiply them all at once?

Example:

arr = [[1,1,1], [1,1,1],[1,1,1]]

A=
[2 2 2]
[2 2 2]

So I need to multiply Av for each v in arr. The result:

arr = [[6,6], [6,6], [6,6]]

Is there a faster way than:

new_arr = []
for v in arr:
    sol = np.matmul(A, v)
    new_arr.append(sol)

Upvotes: 2

Views: 4184

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22043

Seems like you want a dot product:

new_arr = np.dot(arr, A.T)

where arr and A are numpy arrays:

arr = np.array([[1,1,1], [1,1,1],[1,1,1]])
A = np.array([[2,2, 2],[2,2,2]])

Result:

array([[6, 6],
       [6, 6],
       [6, 6]])

According to your edit, the dot product you want may be:

new_arr = np.dot(A, arr).T

Both return the same, but it's not the same computation.

Upvotes: 3

Related Questions