8

Can I use the Eigen library to get the rotation matrix which rotates vector A to vector B? I have been searching for a while, but cannot find related api.

LittleSweet
  • 534
  • 2
  • 6
  • 9
  • "The" rotation matrix which rotates vector A to vector B is ambiguous: there are multiple rotation matrices which send A to B. The method provided in the answer gives one such matrix. – Stéphane Laurent Aug 29 '18 at 14:18

1 Answers1

15

You first have to construct a quaternion and then convert it to a matrix, for instance:

#include <Eigen/Geometry>
using namespace Eigen;

int main() {
  Vector3f A, B;
  Matrix3f R;
  R = Quaternionf().setFromTwoVectors(A,B);
}
ggael
  • 28,425
  • 2
  • 65
  • 71
  • Worth noting that this requires an additional `.toRotationMatrix()` after `(A,B)` to work, as `R` is a Matrix. – Bill Cheatham Sep 10 '13 at 10:08
  • 1
    No, there is an overload of operator= that makes it work. However, the respective is explicit, therefore `Matrix3f R = Quaternionf().setFromTwoVectors(A,B);` requires `.toRotationMatrix()` or to explicit cast to a `Matrix3f(.)`, or to explicitly call the ctor with `Matrix3f R(Quaternionf().setFromTwoVectors(A,B));` – ggael Sep 11 '13 at 08:20
  • Sorry my mistake! Missed that slight subtlety. Thanks for explaining the differences. – Bill Cheatham Sep 11 '13 at 16:55
  • Is there an option for 2D vectors? If my understanding of Quaternions is correct (which I doubt, because I've never worked with them), they're specifically for 3D stuff. – RL-S Jul 29 '20 at 09:30