Anthony Lethuillier
Anthony Lethuillier

Reputation: 1539

List of vectors multiplied by one matrix with numpy einsum

I have a 3x3 matrix and I would like to multiply each vector in a list by this matrix.

This can be done easily with a loop:

import numpy as np

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

for elem in b:
   print(a.dot(elem))

To make it quicker I have tried using numpy.einsum but I am not able to do the correct formulation.

I have tried np.einsum('ij,ji->ij', a, b) but this results in ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,3)->(3,3) (2,3)->(3,2)

Any advice ?

Upvotes: 1

Views: 578

Answers (1)

hpaulj
hpaulj

Reputation: 231385

In [489]: for elem in b:
     ...:     print(a.dot(elem))
     ...:     
[ 2 -1  3]
[ 5 -4  6]

first step - you are iterating the first dimension of b, and expecting that in the result as well:

np.einsum(',i->i', a, b)

dot pairs the last dim of a with the only dim of elem, the 2nd dim of b - and sums them:

np.einsum(' j,ij->i', a, b)

Now fill in the first dimension of a, which passes through as the last dim of the result:

In [495]: np.einsum('kj,ij->ik', a, b)
Out[495]: 
array([[ 2, -1,  3],
       [ 5, -4,  6]])

Switch the arguments around, and a regular 2d dot product appears:

In [496]: np.einsum('ij,kj->ik', b, a)
Out[496]: 
array([[ 2, -1,  3],
       [ 5, -4,  6]])
In [497]: b.dot(a.T)    # b@(a.T)
Out[497]: 
array([[ 2, -1,  3],
       [ 5, -4,  6]])

Upvotes: 2

Related Questions