Sunday, December 7, 2014

Conversion between Quaternion and rotation matrix

There are different ways to represent rotation in 3D space including Quaternion, rotation matrix and others. Often people need to convert between them. Here we want to share some Matlab scripts to convert between Quaternion and rotation matrix. Rotation matrix, R, is a 3x3 unitary matrix. The quaternion has four element, w, x, y, z whereas w is the rotation angle and x,y,z represent the rotation axis. w^2+x^2+y^2+z^2=1.

The function to convert quaternion to rotation matrix R:
 function R = quaternion2R(w, x, y, z)  
 R(1,1) = 1-2*y^2-2*z^2;  
 R(1,2) = 2*x*y-2*z*w;  
 R(1,3) = 2*x*z+2*y*w;  
 R(2,1) = 2*x*y+2*z*w;  
 R(2,2) = 1-2*x^2-2*z^2;  
 R(2,3) = 2*y*z-2*x*w;  
 R(3,1) = 2*x*z-2*y*w;  
 R(3,2) = 2*y*z+2*x*w;  
 R(3,3) = 1-2*x^2-2*y^2;  


The function to convert rotation matrix R to quaternion:
 function [w,x,y,z] = R2quaternion(R)  
 t = R(1,1)+R(2,2)+R(3,3);  
 r = sqrt(1+t);  
 s = 0.5/r;  
 w = 0.5*r;  
 x = (R(3,2)-R(2,3))*s;  
 y = (R(1,3)-R(3,1))*s;  
 z = (R(2,1)-R(1,2))*s;  

No comments:

Post a Comment