Home > Net >  Rotating a vector in 2D
Rotating a vector in 2D

Time:01-16

My problem is attempting to rotate a vector v by the rotation matrix R such that v'=Rv where phi is in degrees and v' is v rotated by angle phi.

This is what I've tried so far:

import numpy as np

def rotation(phi,v):
    theta=np.radians(phi)
    c=np.cos(theta)
    s=np.sin(theta)
    R=np.array((c,-s),(s,c))
    v_prime = R@v
    return(v_prime)

but when i test it i get -1.0, and not the array [-1,0] which is what i should get.

print(rotation(90,[0,1]))

CodePudding user response:

Let's add a print to your function:

In [4]: def rotation(phi,v):
   ...:     theta=np.radians(phi)
   ...:     c=np.cos(theta)
   ...:     s=np.sin(theta)
   ...:     R=np.array((c,-s),(s,c))
   ...:     print(R)
   ...:     v_prime = R@v
   ...:     return(v_prime)
   ...:     

In [4]: 

In [5]: rotation(90,[0,1])
[ 6.123234e-17 -1.000000e 00]
Out[5]: -1.0

Notice that R is a 2 element array, not the 4 square one you wanted. The calling signature for np.array is: np.array(alist, dtype). You gave it two tuples (here the difference between list and tuple isn't important). Actually I'm a little surprised because the second tuple doesn't look like a valid dtype. In any the correction should be obvious - the first argument should be a list (or tuple) of tuples, [(c,-s),(s,c)]

In [6]: def rotation(phi,v):
   ...:     theta=np.radians(phi)
   ...:     c=np.cos(theta)
   ...:     s=np.sin(theta)
   ...:     R=np.array([(c,-s),(s,c)])
   ...:     print(R)
   ...:     v_prime = R@v
   ...:     return(v_prime)
   ...:     

In [7]: rotation(90,[0,1])
[[ 6.123234e-17 -1.000000e 00]
 [ 1.000000e 00  6.123234e-17]]
Out[7]: array([-1.000000e 00,  6.123234e-17])

Now R is correct 2d array, and the result is a 1d array. Don't be thrown by the e-17 value - that's close to a float 0.

In [8]: rotation(45,[0,1])
[[ 0.70710678 -0.70710678]
 [ 0.70710678  0.70710678]]
Out[8]: array([-0.70710678,  0.70710678])

CodePudding user response:

The correct version of your code is:

import numpy as np

def rotation(phi,v):
    theta=np.radians(phi)
    c=np.cos(theta)
    s=np.sin(theta)
    R=np.array([[c,-s],[s,c]]) 
    v_prime = R.dot(v)            
    return(v_prime)

    
print(rotation(90,[0,1]))

CodePudding user response:

Try this -

  1. You need to fix your numpy array for rotation matrix np.array((c,-s),(s,c))
  2. You need to take dot product and then .round() the results.
import numpy as np

def rot(phi,arr):
    phi = np.deg2rad(phi)    #OR np.radians(phi)
    mat = np.array([[np.cos(phi), -np.sin(phi)], 
                    [np.sin(phi), np.cos(phi)]])
    
    out = (mat @ arr).round()
    return out


phi = 90
arr = np.array([0,1])

rot(90,arr)
array([-1.,  0.])

At the end, you have to round the float values to get what you want.

  • Related