If you need to calculate a rotation matrix from Euler angles, you will have realised that it is not easy to find something usable in C#. It is necessary to rely on development tools such as Unity or similar to find ready-made functions.

Today we are going to look at a solution written in C# which will allow us to solve the problem without too much  headaches .

What I am presenting here does not make use of special libraries, so it can be compiled in .NET Core, which guarantees portability on all operating systems supported by the Microsoft framework.

If you are looking for a solution to do the reverse operation, i.e. to derive Euler angles from a rotation matrix, please refer to this article.

Euler Angles to Rotation Matrix

Without wasting any time, here is the solution that allows you, starting from 3 Euler angles (rotation with respect to the X, Y and Z axis), to obtain the relative rotation matrix. The result is strictly dependent on the type of convention you need to use when applying the rotations. In the code in question, I take into account the 3 classic rotation sequences: XYZ, ZYZ and ZYX.

Copy to Clipboard

To begin with, let us define two enums that will make the code more readable. In lines 1 – 5, we define the various types of angle units that we want to manage, in our case degrees and radians. On lines 7 – 12, we describe the various axis rotation sequences that we will be managing.

The function, as described by the signature in line 14, takes as input:

  • an array of doubles of 3 elements containing the Euler angles;
  • the type of rotation of the axes;
  • the unit of measurement of the angles passed as first parameter;

and returns a 3 x 3 matrix containing the rotation matrix.

To test the code we have just written, we write a simple program that performs the calculation of the rotation:

  • Rx = 180;
  • Ry = 0;
  • Rz = 180.
Copy to Clipboard

The output result will be the 3 x 3 matrix in which the elements are stored in row-major order (i.e. row by row).

rotM[0,0] rotM[0, 1] rotM[0, 2]
rotM[1,0] rotM[1,1] rotM[1,2]
rotM[2,0] rotM[2,1] rotM[2,2]

Conclusions

The rotation matrix is nothing more than a matrix operator that allows a vector to be rotated around a given axis in space. It is a very useful tool in several application fields, such as in robotics in solving inverse kinematics problems or in reference system transformations.

In this short article, we have presented a solution in C# that allows the calculation of the rotation matrix from a configuration of Euler angles.