How to create and apply a rotation matrix using python ?

Published: February 22, 2019

DMCA.com Protection Status

To create and apply a rotation matrix using python, a solution is to use numpy:

\begin{equation}
\left( \begin{array}{cc}
\cos(\theta) & -\sin(\theta) \\
\sin(\theta) & \cos(\theta)
\end{array}\right)
.
\left( \begin{array}{c}
x \\
y
\end{array}\right)
\end{equation}

import numpy as np

theta = np.radians(30)

r = np.array(( (np.cos(theta), -np.sin(theta)),
               (np.sin(theta),  np.cos(theta)) ))

print('rotation matrix:')
print(r)

v = np.array((0,1))

print('vector v: ')
print(v)

print('apply the rotation matrix r to v: r*v')
print( r.dot(v) )

returns

rotation matrix:

[[ 0.8660254 -0.5      ]
 [ 0.5        0.8660254]]

vector v: 
[0 1]

apply the rotation matrix r to x: r*v
[-0.5        0.8660254]

\begin{equation}
\left( \begin{array}{cc}
\cos(30) & -\sin(30) \\
\sin(30) & \cos(30)
\end{array}\right)
.
\left( \begin{array}{c}
0 \\
1
\end{array}\right)
=
\left( \begin{array}{c}
-0.5 \\
0.866
\end{array}\right)
\end{equation}

References