title: Efficient way to calculate a 3x3 rotation matrix from the rotation defined by two 3D Vectors
body: <p>While I've found 2 solutions to this, I was curious if there is well known method to perform this operation since it seems a fairly common task.</p>
  <p>Here are the 2 obvious methods psudo-code...</p>
  <h1>Axis Angle</h1>
  <p>This is quite logical, but calls <code>sin</code> twice and <code>cos</code> once (in the angle calculation and axis angle to matrix conversion).</p>
  <pre class="lang-c prettyprint-override"><code>Matrix3x3 rotation_between_vectors_to_matrix(const Vector v1, const Vector v2)
  {
      angle = v1.angle(v2);
      axis  = v1.cross(v2);
  
      /* maths for this is well known */
      Matrix3x3 matrix = axis_angle_to_matrix(axis, angle);
  
      return matrix;
  }
  </code></pre>
  <p><strong>Edit</strong>: The most straightforward function is a quite slow, however as has been pointed out in the replies here: calculating the angle can be avoided by getting <code>angle_sin</code> and <code>angle_cos</code>, from the axis length and <code>v1,v2</code> dot product respectively.</p>
  <h1>Difference between two matrices</h1>
  <p>Here's another method I found which constructs two 3x3 matrices from the vectors and returns the difference.</p>
  <p>However this is slower then axis/angle calculation which can be optimized (mentioned above).</p>
  <p><em>Note. this assumes both vectors are normalized, matrix is column-major (OpenGL).</em></p>
  <pre class="lang-c prettyprint-override"><code>Matrix3x3 rotation_between_vectors_to_matrix(const Vector v1, const Vector v2)
  {
      Matrix3x3 m1, m2;
  
      axis = v1.cross(v2);
      axis.normalize();
  
      /* construct 2 matrices */
      m1[0] = v1;
      m2[0] = v2;
  
      m1[1] = axis;
      m2[1] = axis;
  
      m1[2] = m1[1].cross(m1[0]);
      m2[2] = m2[1].cross(m2[0]);
  
      /* calculate the difference between m1 and m2 */
      m1.transpose();
  
      Matrix3x3 matrix = m2 * m1;
  
      return matrix;
  }
  </code></pre>
  <p>Are there better ways to perform this calculation?</p>
  <p><strong>Edit:</strong> The purpose of this question is NOT to micro-optimize and benchmark each method. Instead - I was curious if there is some totally different and superior method which I didn't know about.</p>
  <hr />
  <p><strong>Note</strong>: I purposefully left out checks for the degenerate case for co-linear vectors (where the axis is zero length), to keep the examples simple.</p>