%% Quaternion Math
% Quaternions have well-defined arithmetic operations. To apply these operations, first define two quaternions by specifying their real-number parts.

q1 = quaternion(1,2,3,4)
q2 = quaternion(-5,6,-7,8)

%
% Addition of quaternions is similar to complex numbers, where parts are added independently.

q1 + q2

%
% Subtraction of quaternions works similar to addition of quaternions.

q1 - q2

%
% Because the complex elements of quaternions must satisfy the equation
% i^2 =j^2 =k^2 =\textrm{ijk}=-1,
% multiplication of quaternions is more complex than addition and subtraction. Given this requirement, multiplication of quaternions is not commutative. That is, when multiplying quaternions, reversing the order of the quaternions changes the result of their product.

q1 * q2
q2 * q1

%
% However, every quaternion has a multiplicative inverse, so you can divide quaternions. Right division of q1 by q2 is equivalent to q1(q2^{-1}).

q1 ./ q2

%
% Left division of q1 by q2 is equivalent to (q2^{-1})q1.

q1 .\ q2

%
% The conjugate of a quaternion is formed by negating each of the complex parts, similar to conjugate of a complex number.

conj(q1)

%
% To describe a rotation using a quaternion, the quaternion must be a unit quaternion. A unit quaternion has a norm of 1, where the norm is defined as
% \textrm{norm}\left(q\right)=\sqrt{a^2 +b^2 +c^2 +d^2 }.
% Normalize a quaternion.

qNormalized = normalize(q1)

%
% Verify that this normalized unit quaternion has a norm of 1.

norm(qNormalized)

% The rotation matrix for the conjugate of a normalized quaternion is equal to the inverse of the rotation matrix for that normalized quaternion.

rotmat(conj(qNormalized),'point')
inv(rotmat(qNormalized,'point'))

%
% Copyright 2019 The MathWorks, Inc.