Home > Blockchain >  How to multiply several vectors by one matrix at once (in numpy)?
How to multiply several vectors by one matrix at once (in numpy)?

Time:03-30

I have a 2x2 rotation matrix and several vectors stored in a Nx2 array. Is there a way to rotate them all (i.e. multiply them all by the rotation matrix) at once?

I'm sure there is a numpy method for that, it's just not obvious.

import numpy as np

vectors = np.array( ( (1,1), (1,2), (2,2), (4,2) )  ) # 4 2D vectors
ang = np.radians(30)
m = np.array( ( (np.cos(ang), -np.sin(ang)),
                (np.sin(ang),  np.cos(ang)) ))        # 2x2 rotation matrix

# rotate 1 vector:
m.dot(vectors[0,:])

# rotate all vectors at once??

CodePudding user response:

Because m has shape (2,2) and vectors has shape (4,2), you can simply do

dots = vectors @ m.T

Then each row i contains the matrix-vector product m @ vectors[i, :].

CodePudding user response:

Another option is to use the powerful einsum function and do:

dots = np.einsum("ij,kj->ik", vectors, m)
  • Related