0

Is there an efficient way to multiply many different rotation matrices to the same vector?

Right now I am doing the following, extremely slow procedure

for i, rm in enumerate(ray_rotation_matrices):
        scan_point = rm * np.vstack([scale, 0, 0, 1])
        scan_points[i] = np.hstack(scan_point[:3])

Each rm is a 4x4 matrix for homogenous coordinates. Can I somehow broadcast, but how do I make sure it applies matrix multiplication and not element wise product?

I want to get rid of the for loop...

El Dude
  • 5,328
  • 11
  • 54
  • 101

1 Answers1

3

Use one large array and the matrix multiplication operator @. It is vectorized out of the box. Example:

# a stack of five 4x4 matrices
>>> m = np.random.random((5, 4, 4))
>>> v = np.random.random((4,))

# all five matrix vector products in one go
>>> m@v
array([[1.08929927, 0.98770373, 1.0470138 , 1.266117  ],
   [0.71691193, 0.68655178, 1.25601832, 1.22123406],
   [1.3964922 , 1.02123137, 1.03709715, 0.72414757],
   [0.9422159 , 0.84904553, 0.8506686 , 1.29374861],
   [1.02159382, 1.36399314, 1.06503775, 0.56242674]])

# doing it one-by-one gives the same answer
>>> [mi@v for mi in m]
[array([1.08929927, 0.98770373, 1.0470138 , 1.266117  ]), array([0.71691193, 0.68655178, 1.25601832, 1.22123406]), array([1.3964922 , 1.02123137, 1.03709715, 0.72414757]), array([0.9422159 , 0.84904553, 0.8506686 , 1.29374861]), array([1.02159382, 1.36399314, 1.06503775, 0.56242674])]
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Thanks. I just arrived at `np.dot(rotation_matrices, np.vstack([scale, 0, 0, 1]))[:, :3, -1]`. Think this is the same, but I didn't know the `@` operator existed. – El Dude Mar 30 '18 at 01:15