title: How to calculate the rotation angles needed on X and Z to align two vectors
body: <p>I am trying to rotate vector1 (red) so that it aligns with vector2 (blue) in 3D space. However, only rotations around the X and Z axis should be used. </p>
  
  <p><img src="https://i.stack.imgur.com/L7qEJ.png" alt="vector sample representation"></p>
  
  <p>So far, I have solved this using an optimizing algorithm that tries to minimize the angles around the X and Z-Axis between the vectors. This worked in most cases quite well but since I have to compute a lot of those vectors it is too slow. </p>
  
  <p>The code i used for the optimization approach:</p>
  
  <pre><code>vector1 = np.array([0., -1., 0.])
  vector2 = np.array([0.2, -0.2, -0.5])
  
  def find_a_c(x, *args):
      vector1, vector2 = args[0], args[1]
      angle_x, angle_z = x[0], x[1]
  
      # Rotation matrices to rotate around X and Z
      Rx = np.array([[1., 0., 0.],
                    [0., np.cos(angle_x), -np.sin(angle_x)],
                    [0., np.sin(angle_x), np.cos(angle_x)]])
  
      Rz = np.array([[np.cos(angle_z), -np.sin(angle_z), 0.],
                    [np.sin(angle_z), np.cos(angle_z), 0.],
                    [0., 0., 1.]])
  
      vector1 = vector1.dot(Rx).dot(Rz)
  
      # calulate the angle between the vectors around X and Z
      angle_x = angle_between_vectors([vector2[1], vector2[2]], [vector1[1], vector1[2]])
      angle_z = angle_between_vectors([vector2[0], vector2[1]], [vector1[0], vector1[1]])
  
      return np.abs(angle_x) + np.abs(angle_z)
  
  solution = minimize(fun=find_a_c,
                      x0=[0., 0.],
                      args=(vector1, vector2))
  
  angle_x, angle_z = solution.x[0], solution.x[1]
  print("Angle around X: {}°\nAngle around Z: {}°".format(np.rad2deg(angle_x), np.rad2deg(angle_z)))
  </code></pre>
  
  <p>Prints:</p>
  
  <pre><code>Angle around X: -60.46948402478365°
  Angle around Z: -45.0000003467713°
  </code></pre>
  
  <p>Now I'm looking for an analytical approach that solves my problem. E.g. a rotation matrix formed with the two rotation angles (around X and Z) to align vector1 to vector2.</p>