Getting the angle between two vectors is well known. But finding the ‘rotation angle’ from one vector to another needs a bit more consideration. The following functions can handle this.

import numpy as np def calculate_rotation_angle_from_vector_to_vector(a,b): """ return rotation angle from vector a to vector b, in degrees. Args: a : np.array vector. format (x,y) b : np.array vector. format (x,y) Returns: angle [float]: degrees. 0~360 """ unit_vector_1 = a / np.linalg.norm(a) unit_vector_2 = b / np.linalg.norm(b) dot_product = np.dot(unit_vector_1, unit_vector_2) angle = np.arccos(dot_product) angle = angle/ np.pi * 180 c = np.cross(b,a) if c>0: angle +=180 return angle

This function will use cross product between two vectors to identify if the rotation direction is CW or CCW. This function will return rotation angle in CCW direction in degrees.

## 3 Comments

## Augusto de Lelis Araujo · March 27, 2022 at 10:53 pm

??????????????????????????????????????????????????????????

a = [1,0] and b = [1,0] >> angle = 0º

a = [1,-0.01] and b = [1,0] >> angle = 180.57293869768262º

??????????????????????????????????????????????????????????

## Augusto de Lelis Araujo · March 27, 2022 at 11:20 pm

import numpy as np

u = [1.0, -0.01]

u = u / np.linalg.norm(u)

v = [1.0, 0.0] # vector fixed (reference)

dot_product = np.dot(u, v)

angle = np.arccos(dot_product) / np.pi * 180

if (u[1] >= 0.0):

angle = angle

if (u[1] < 0.0):

angle = 360 – angle

print(str(angle) + 'º')

## minhln14 · December 27, 2022 at 1:18 pm

def create_rotation_matrix(vector_rot, vector_base):

“””

Create matrix vector rotation [ cos(theta) -sin(theta)

sin(theta) cos(theta) ]

from vector_rot to vector_base

“””

vector_rot = vector_rot / np.linalg.norm(vector_rot)

vector_base = vector_base / np.linalg.norm(vector_base)

# Calculate radian angle

theta = np.arctan2(vector_base[1], vector_base[0]) – np.arctan2(vector_rot[1] , vector_rot[0])

# Calculate matrix

c, s = np.cos(theta), np.sin(theta)

matrix = np.array(((c, -s), (s, c)))

return matrix