Search code examples
pythonarraysnumpymatrixrotational-matrices

Python Numpy Apply Rotation Matrix to each line in array


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.


Solution

  • 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