简体   繁体   中英

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

I have a 2x2 rotation matrix and several vectors stored in a Nx2 array. Is there a way to rotate them all (ie 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??

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, :] .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM