title: Conversion euler to matrix and matrix to euler
body: <p>I'm trying to convert a 3D rotation described in term of euler angles into a matrix and then back, using .NET/C#. My conventions are: </p>
  
  <ul>
  <li>left handed system (x right, y top, z forward)</li>
  <li>order of rotations: heading around y, pitch around x, bank around z</li>
  <li>rotations are positive using the left hand rule (thumb pointing to +infinity)</li>
  </ul>
  
  <p>My trial is:</p>
  
  <p><strong>Euler to matrix</strong> (I've removed the x,y,z translation part for simplification)</p>
  
  <pre><code>Matrix3D matrix = new Matrix3D() {
      M11 =   cosH * cosB - sinH * sinP * sinB,
      M12 = - sinB * cosP,
      M13 =   sinH * cosB + cosH * sinP * sinB,
      M21 =   cosH * sinB + sinH * sinP * cosB,
      M22 =   cosB * cosP,
      M23 =   sinB * sinH - cosH * sinP * cosB,
      M31 = - sinH * cosP,
      M32 = - sinP,
      M33 =   cosH * cosP,
  };
  </code></pre>
  
  <p><strong>Matrix to Euler</strong></p>
  
  <pre><code>const double RD_TO_DEG = 180 / Math.PI;            
  double h, p, b; // angles in degrees
  
  // extract pitch
  double sinP = -matrix.M23;            
  if (sinP &gt;= 1) {
      p = 90; }       // pole
  else if (sinP &lt;= -1) {
      p = -90; } // pole
  else {
      p = Math.Asin(sinP) * RD_TO_DEG; }             
  
  // extract heading and bank
  if (sinP &lt; -0.9999 || sinP &gt; 0.9999) { // account for small angle errors
      h = Math.Atan2(-matrix.M31, matrix.M11) * RD_TO_DEG;
      b = 0; }
  else {
      h = Math.Atan2(matrix.M13, matrix.M33) * RD_TO_DEG;
      b = Math.Atan2(matrix.M21, matrix.M22) * RD_TO_DEG; }
  </code></pre>
  
  <p>It must be wrong. If I take 3 angles, convert them into a matrix and convert the matrix back into angles, the result if different than the intial values.</p>
  
  <p>I have browsed several sites with different formulas, starting with euclideanspace.com, but I'm now completely lost, and can't find the right computations. I' appreciate a little help. Is there a mathematician onboard?</p>