Function Repository Resource:

QuaternionToRotationMatrix

Source Notebook

Convert a unit quaternion to an equivalent rotation matrix

Contributed by: Jan Mangaldan

ResourceFunction["QuaternionToRotationMatrix"][w]

converts the unit quaternion w into an equivalent 3×3 rotation matrix.

Details and Options

The argument w should be a numeric Quaternion object, or a scalar that can be converted into one.
If the argument w is not a unit quaternion, ResourceFunction["QuaternionToRotationMatrix"] begins by normalizing it.

Examples

Basic Examples (3) 

Define a quaternion:

In[1]:=
w = ResourceFunction["Quaternion"][5/6, 1/6, 1/2, 1/6]
Out[1]=

Generate a rotation matrix from a unit quaternion:

In[2]:=
ResourceFunction["QuaternionToRotationMatrix"][w] // MatrixForm
Out[2]=

Verify that the result is a rotation matrix:

In[3]:=
OrthogonalMatrixQ[%] && Det[%] == 1
Out[3]=

Scope (4) 

An exact quaternion:

In[4]:=
ResourceFunction["QuaternionToRotationMatrix"][
  ResourceFunction["Quaternion"][2/7, 5/7, 4/7, 2/7]] // MatrixForm
Out[4]=

An approximate MachinePrecision quaternion:

In[5]:=
ResourceFunction["QuaternionToRotationMatrix"][
  N[ResourceFunction["Quaternion"][2/7, 5/7, 4/7, 2/7]]] // MatrixForm
Out[5]=

An approximate arbitrary precision quaternion:

In[6]:=
ResourceFunction["QuaternionToRotationMatrix"][
  N[ResourceFunction["Quaternion"][2/7, 5/7, 4/7, 2/7], 25]] // MatrixForm
Out[6]=

QuaternionToRotationMatrix threads over lists:

In[7]:=
ResourceFunction[
 "QuaternionToRotationMatrix"][{ResourceFunction["Quaternion"][0, 0, 1, 0], ResourceFunction["Quaternion"][0, 0, 0, 1]}]
Out[7]=

Applications (2) 

Create a unit quaternion:

In[8]:=
uq = N[ResourceFunction["Quaternion"][(1 + Sqrt[3])/4, (1 - Sqrt[3])/
   4, (1 + Sqrt[3])/4, (1 - Sqrt[3])/4]]
Out[8]=

Also define a vector to be rotated:

In[9]:=
vec = RandomVariate[NormalDistribution[], 3]
Out[9]=

Transform the vector using the quaternion representation of a rotation:

In[10]:=
Rest[Apply[
  List, (uq ** Apply[ResourceFunction["Quaternion"], Prepend[vec, 0]]) ** Power[uq, -1]]]
Out[10]=

Transform the vector using the rotation matrix representation to get the same result:

In[11]:=
ResourceFunction["QuaternionToRotationMatrix"][uq].vec
Out[11]=

Get the axis-angle representation of a quaternion:

In[12]:=
ResourceFunction["AxisAngle"][
 ResourceFunction["QuaternionToRotationMatrix"][
  ResourceFunction["Quaternion"][2/9, 5/9, 2/3, 4/9]]]
Out[12]=

Recover the original quaternion:

In[13]:=
Apply[ResourceFunction["Quaternion"], Prepend[Sin[First[%]/2] Last[%], Cos[First[%]/2]]] // FullSimplify
Out[13]=

Version History

  • 1.0.0 – 23 December 2020

Source Metadata

Related Resources

License Information