This post shows how to decompose a 3×3 rotation matrix into the 3 elementary Euler angles, sometimes referred to as yaw/pitch/roll, and going the other way around. The technique I’m presenting is based off http://planning.cs.uiuc.edu/node102.html.
If you have ever seen Wikipedia’s entry on Rotation matrix or Euler angles, you will have no doubt been swamped to your neck with maths equations all over the place, depending how tall your neck is. It turns out there is no single correct answer on defining a rotation matrix in terms of Euler angles. There are a few ways to accomplish it and all of them are valid. But that’s okay, I’ll just show one way, which should be adequate for most applications. I won’t go into any maths derivation, aiming to keep this post implementation friendly.
Decomposing a rotation matrix
Given a 3×3 rotation matrix
The 3 Euler angles are
Here atan2 is the same arc tangent function, with quadrant checking, you typically find in C or Matlab.
Composing a rotation matrix
Given 3 Euler angles , the rotation matrix is calculated as follows:
Note on angle ranges
The Euler angles returned when doing a decomposition will be in the following ranges:
If you keep your angles within these ranges, then you will get the same angles on decomposition. Conversely, if your angles are outside these ranges you will still get the correct rotation matrix, but the decomposed values will be different to your original angles.
The Octave/Matlab script contains the decompose/compose function and a demo on using it. It picks random Euler angles, makes a rotation matrix, decomposes it and verifies the results are the same. An example output
octave:1> rotation_matrix_demo Picking random Euler angles (radians) x = -2.6337 y = -0.47158 z = -1.2795 Rotation matrix is: R = 0.25581 -0.77351 0.57986 -0.85333 -0.46255 -0.24057 0.45429 -0.43327 -0.77839 Decomposing R x2 = -2.6337 y2 = -0.47158 z2 = -1.2795 err = 0 Results are correct!