Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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??
like image 469
Osman-pasha Avatar asked Sep 05 '25 03:09

Osman-pasha


2 Answers

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

like image 80
joni Avatar answered Sep 07 '25 23:09

joni


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

dots = np.einsum("ij,kj->ik", vectors, m)
like image 40
Matt Pitkin Avatar answered Sep 08 '25 01:09

Matt Pitkin