   My Coding > Programming language > Python > Python FAQ > Python: How to make random rotation matrix

# Python: How to make random rotation matrix

## Random rotation matrix

This question can be rephrased into a question, how to calculate a random rotation. This rotation should not distort proportions of an original object. Furthermore, the determinant of this matrix should be equal 1 by default.

The easiest way to do it, is a make a random rotation along three orthogonal axises and multiply these matrices together. The easiest way to do in in python with numpy library.

### 2d rotation matrix

As I was show before 2D rotation matrix can be written as a rotation in the plane around perpendicular axis. Therefore the following two matrices will do virtually the same job

``````
|cos(θ), -sin(θ)|
|sin(θ),  cos(θ)|

|cos(θ), -sin(θ),    0|
|sin(θ),  cos(θ),    0|
|     0,       0,    1|``````

And now we can repeat this operation for three axises

## Python code for random rotation matrix

``````
import numpy as np

def rand_matrix():
''' random rotation matrix '''
a = np.random.rand() * 2 * np.pi # random angle [0, 2pi)
c, s = np.cos(a), np.sin(a)
r1 = np.array([[c, -s, 0],       # rotation around Z
[s,  c, 0],
[0,  0, 1]
])

a = np.random.rand() * 2 * np.pi # random angle [0, 2pi)
c, s = np.cos(a), np.sin(a)
r2 = np.array([[c,  0, -s],       # rotation around Y
[0,  1,  0],
[s,  0,  c]
])

a = np.random.rand() * 2 * np.pi # random angle [0, 2pi)
c, s = np.cos(a), np.sin(a)
r3 = np.array([[1,  0,  0],       # rotation around X
[0,  c, -s],
[0,  s,  c]
])
return r1.dot(r2).dot(r3)         # multiply 3 matrices

# tests
M = rand_matrix()

print(M)
# [[ 0.98871429  0.09682133 -0.11432275]
#  [ 0.10148702 -0.9941958   0.03570861]
#  [-0.11020184 -0.04690788 -0.99280169]]
print(np.linalg.det(M)) # 1.0000000000000002``````

Published: 2021-11-14 11:31:19

### 9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. 