Rotation matrix to quaternion implementation

2.4k Views Asked by At

I'm looking at this piece of MATLAB source code which is meant to convert a rotation matrix into a quaternion. I'm a little confused about what it claims to do in its header.

% rot2quat - converts a rotation matrix (3x3) to a unit quaternion(3x1)
%
%    q = rot2quat(R)
% 
%    R - 3x3 rotation matrix, or 4x4 homogeneous matrix 
%    q - 3x1 unit quaternion
%        q = sin(theta/2) * v
%        theta - rotation angle
%        v     - unit rotation axis, |v| = 1
%
%

The way they've defined $q$ is a little strange because I'm used to seeing $q = cos(\theta/2) + sin(\theta/2)v$ where $cos(\theta/2)$ is the scalar component of the quaternion and $sin(\theta/2)v$ expands into the vector part of the quaternion. Perhaps the fact that it's a "unit" quaternion has something to do with it? I'm not too familiar with unit quaternions.

2

There are 2 best solutions below

7
On

The map from unit quaternions to $3\times3$ rotation matrices is a double cover. Both $q,-q\in\mathcal{S}^1(\mathbb{H})$ map to the same rotation matrix. As such, the inverse map rot2quad should be set valued. Here, they can recover $|\cos\theta/2|$ from the constraint $|q|=1$, but they do lose the sign of $\theta$. This could cause problems because then quad2rot(rot2quad($R$)) yields two possible answers $R_1$ and $R_2$, and only one of them equals $R$. This problem is not due to the double cover, but rather the omission of the real part. Perhaps they only need the pure quaternion part for whatever it is they do.

0
On

3D vector definitely cannot be a unit quaternion. Vector "q" has to be a parameterization similar to quaternion logarithm.

$\exp(b \theta / 2) = \cos (\theta / 2) - b \sin (\theta / 2)$

My guess is that instead of a proper quaternion logarithm, which would be $q = b \theta / 2$, they are adopting the unusual form $q = b \sin (\theta / 2)$ which is a poor choice from mathematical point of view since the original sign of $\theta$ cannot be recovered as pointed out by @Asdf answer.

Anyway, that choice might be ok in a particular application in which all angles are constrained to be positive or negative. We cannot know without more context.