Rotation matrix from one vector to another

QuestionsCategory: QuestionsRotation matrix from one vector to another
mrtester asked 3 years ago

I want to create a $3\times 3$ rotation matrix that rotates from one vector $\mathbf u$ to another $\mathbf v$. 
Can someone help? Thanks!

1 Answers
Tomas Akenine-Möller Staff answered 3 years ago

The classical answer is that you can create an axis of rotation, $\mathbf a= \mathbf u \times \mathbf v / ||\mathbf u \times \mathbf v ||$, which is normalized, and compute the angle between $\mathbf u$ and $\mathbf v$, i.e., $\alpha = \arccos(\mathbf u \cdot \mathbf v)$. The rotation matrix is then:
\mathbf M =
a_x^2(1-c) +c & a_xa_y(1-c) – sa_z & a_xa_z(1-c)+sa_y\\
a_xa_y(1-c) + sa_z & a_y^2(1-c) +c & a_ya_z(1-c)-sa_x\\ a_xa_z(1-c) – sa_y & a_ya_z(1-c) + sa_x & a_z^2(1-c) +c
where $c=\cos\alpha$ and $s=\sin\alpha$. It should be possible to show that $\mathbf v = \mathbf M\mathbf u$.
If you want an efficient implementation where $\mathbf u$ and $\mathbf v$ are assumed to be unit vectors to start with, then one can avoid all trigonometric functions (e.g., since $\cos\alpha = \mathbf u \cdot \mathbf v$ etc) and square roots as well with a little extra derivation work.
You can read more about matrices in Chapter 6 in the Immersive Linear Algebra book.