Rotation matrix from 2 vectors (3D)

We want to find the rotation matrix A that can be applied to a vector v1 (x1, y1, z1) so that it points in the same direction as does the vector v2 (x2, y2, z2).

 

This will be done in 2 steps :

    Step 1 : find the normalized quaternion that represents the rotation

    Step 2 : calculate the rotation matrix from the quaternion

 

Step 1   :  from

 http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/minorlogic.htm

 

d = x1x2 + y1y2+ z1z2

q1 = y1z2 – y2z1

q2 = z1x2 – z2x1

q3 = x1y2 – x2y1

q4 = sqrt((x1x1 + y1y1 + z1z1) * (x2x2 + y2y2 + z2z2)) + d

norm = sqrt(q1q1 + q2q2 + q3q3 + q4q4)

q1 = q1 / norm

q2 = q2 / norm

q3 = q3 / norm

q4 = q4 / norm

 

 

Step 2  :  from

http://en.wikipedia.org/wiki/Rotation_representation_(mathematics)#Quaternions