6

I have a rotation matrix, and am using .dot to apply it to new values. How can I apply it to each row in a numpy array?

Numpy array looks like:

 [-0.239746 -0.290771 -0.867432]
 [-0.259033 -0.320312 -0.911133]
 [-0.188721 -0.356445 -0.889648]
 [-0.186279 -0.359619 -0.895996]

Want to do something like, for each line in array, rotation_matrix.dot(line) and add each line to new array

Not too familiar with Numpy so I'm sure it's something pretty simple that I just can't grasp.

bhreathn711
  • 79
  • 1
  • 2
  • 6
  • What's the shape of `rotation_matrix`? Did you write any code to implement that pseudo code? From what I understand, you could try : `np.tensordot(rotation_matrix,input_array,axes=(1,1)) `. – Divakar Jul 14 '16 at 10:53

3 Answers3

10

Multiplying the a matrix with your rotation matrix rotates all columns individually. Just transpose forth, multiply and transpose back to rotate all rows:

a = np.array([
 [-0.239746,-0.290771,-0.867432],
 [-0.259033,-0.320312,-0.911133],
 [-0.188721,-0.356445,-0.889648],
 [-0.186279,-0.359619,-0.895996],
])

rot = np.array([
 [0.67151763, 0.1469127, 0.72627869],
 [0.47140706, 0.67151763, -0.57169875],
 [-0.57169875, 0.72627869, 0.38168025],
])

print a

print "-----"

for i in range(a.shape[0]):
    print a[i, :]

print "-----"

for i in range(a.shape[0]):
    print rot.dot(a[i, :])

print "-----"

print rot.dot(a.T).T
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
0

Let's assume you have a 3x3 rotation matrix R, and you want to matrix multiply vectors with size 3 as rows ra from array A, to result in rotated vectors rb with size 3 in array B:

import numpy as np

# Define numpy array.
A = np.array([[-0.239746, -0.290771, -0.867432],
              [-0.259033, -0.320312, -0.911133],
              [-0.188721, -0.356445, -0.889648],
              [-0.186279, -0.359619, -0.895996]])

# Define resulting zero array B.
B = np.zeros(A.shape)

# Loop over rows and determine rotated vectors.
for ra,rb in zip(A,B):
    rb = np.dot(R,ra)
Jona
  • 61
  • 1
  • 2
-1
a.dot(rot) 

should do what you want.

Peter
  • 12,274
  • 9
  • 71
  • 86