TExcelTAD
Home › Linear Algebra & Matrix Theory › Rotations: Matrices vs Quaternions

Rotations: Matrices vs Quaternions

A 3D rotation can be stored as a 3×33 \times 3 orthogonal matrix, as three Euler angles, or as a unit quaternion. Matrices are best for transforming many points, Euler angles are easiest for people to type, and quaternions are best for composing and interpolating rotations. This lesson shows why with code, including gimbal lock and slerp.

Three representations

Representation Numbers Strength Weakness
Rotation matrix RR (RTR=IR^T R = I, det⁡R=1\det R = 1) 9 transforms vectors with one product; GPU-native drifts away from orthogonal; awkward to interpolate
Euler angles (yaw, pitch, roll) 3 human-friendly order-dependent; gimbal lock
Unit quaternion qq 4 compact, cheap to compose, smooth interpolation (slerp) less intuitive; qq and −q-q are the same rotation

All three describe the same group SO(3)SO(3) of orthogonal matrices with determinant 1. Game-engine details are in Euler Angles, Axis-Angle and Quaternions.

Gimbal lock

Build a rotation from Euler angles as R=Ry(yaw)⋅Rx(pitch)⋅Rz(roll)R = R_y(\text{yaw}) \cdot R_x(\text{pitch}) \cdot R_z(\text{roll}). When pitch=90∘\text{pitch} = 90^\circ, the roll axis is turned onto the yaw axis, and the two angles do the same thing: only their difference matters. One degree of freedom is lost, which is gimbal lock. The matrix is still a perfectly good rotation; the problem is the parametrization.

python · try it yourself
import numpy as np

def Rx(a): c, s = np.cos(a), np.sin(a); return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])
def Ry(a): c, s = np.cos(a), np.sin(a); return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
def Rz(a): c, s = np.cos(a), np.sin(a); return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
def euler(yaw, pitch, roll):
    return Ry(np.radians(yaw)) @ Rx(np.radians(pitch)) @ Rz(np.radians(roll))

A = euler(30, 90, 10)
B = euler(50, 90, 30)          # yaw and roll both +20°: same difference
print("same matrix at pitch 90:", np.allclose(A, B))
print("same matrix at pitch 80:", np.allclose(euler(30, 80, 10), euler(50, 80, 30)))

# Near the lock, a small change of the actual rotation needs a huge change in the angles
J = np.zeros((9, 3))
for i in range(3):
    d = np.zeros(3); d[i] = 1e-6
    J[:, i] = (euler(*(np.array([30, 89.9, 10]) + d)) - euler(30, 89.9, 10)).ravel() / 1e-6
sv = np.linalg.svd(J)[1] * 180 / np.pi           # per radian instead of per degree
print("singular values of d(matrix)/d(angles) at pitch 89.9:", [round(float(x), 4) for x in sv])
same matrix at pitch 90: True
same matrix at pitch 80: False
singular values of d(matrix)/d(angles) at pitch 89.9: [2.0, 1.4142, 0.0017]

One singular value of the derivative map is almost zero near pitch 90°: some angle change barely moves the rotation, so the reverse direction (finding angles for a desired small rotation) blows up. That is the matrix-calculus signature of gimbal lock, and the SVD is the tool that reveals it.

Quaternions in one page

A quaternion is q=w+xi+yj+zkq = w + xi + yj + zk with i2=j2=k2=ijk=−1i^2 = j^2 = k^2 = ijk = -1. Multiplication is associative but not commutative (ij=kij = k but ji=−kji = -k). A rotation by angle θ\theta about the unit axis n\mathbf{n} is the unit quaternion

q=cos⁡(θ/2)+sin⁡(θ/2)(nxi+nyj+nzk)q = \cos(\theta/2) + \sin(\theta/2)(n_x i + n_y j + n_z k)

and a vector v\mathbf{v} (as the pure quaternion 0+v0 + \mathbf{v}) is rotated by v′=qvq∗\mathbf{v}' = q\mathbf{v}q^*, where q∗=w−xi−yj−zkq^* = w - xi - yj - zk is the conjugate. Composition is multiplication: q2q1q_2 q_1 means "first q1q_1, then q2q_2", like the matrix product R2R1R_2 R_1. Because θ/2\theta/2 appears, qq and −q-q give the same rotation (a double cover).

Every unit quaternion corresponds to a rotation matrix:

R=[1−2(y2+z2)2(xy−wz)2(xz+wy)2(xy+wz)1−2(x2+z2)2(yz−wx)2(xz−wy)2(yz+wx)1−2(x2+y2)]R = \begin{bmatrix} 1 - 2(y^2 + z^2) & 2(xy - wz) & 2(xz + wy) \\ 2(xy + wz) & 1 - 2(x^2 + z^2) & 2(yz - wx) \\ 2(xz - wy) & 2(yz + wx) & 1 - 2(x^2 + y^2) \end{bmatrix}
python · try it yourself
import numpy as np

def qmul(a, b):
    w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
    return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
                     w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
def axis_angle(axis, deg):
    n = np.asarray(axis, float) / np.linalg.norm(axis); h = np.radians(deg) / 2
    return np.concatenate([[np.cos(h)], np.sin(h) * n])
def rotate(q, v):
    conj = q * np.array([1, -1, -1, -1])
    return qmul(qmul(q, np.concatenate([[0.0], v])), conj)[1:]
def to_matrix(q):
    w, x, y, z = q
    return np.array([[1 - 2*(y*y + z*z), 2*(x*y - w*z), 2*(x*z + w*y)],
                     [2*(x*y + w*z), 1 - 2*(x*x + z*z), 2*(y*z - w*x)],
                     [2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x*x + y*y)]])

qz = axis_angle([0, 0, 1], 90)
qx = axis_angle([1, 0, 0], 90)
v = np.array([1.0, 0.0, 0.0])
print("rotate x-axis 90° about z:", np.round(rotate(qz, v), 6) + 0)
q = qmul(qx, qz)                                  # first z, then x
print("first z then x:", np.round(rotate(q, v), 6) + 0)
R = to_matrix(qx) @ to_matrix(qz)
print("matrix product agrees:", np.allclose(to_matrix(q), R), " det =", round(float(np.linalg.det(R)), 6))
print("qx qz == qz qx ?", np.allclose(qmul(qx, qz), qmul(qz, qx)))
rotate x-axis 90° about z: [0. 1. 0.]
first z then x: [0. 0. 1.]
matrix product agrees: True  det = 1.0
qx qz == qz qx ? False

Interpolation: slerp

To blend smoothly between two orientations (animation, camera moves, network smoothing), linearly interpolating matrices fails: (1−t)R0+tR1(1 - t)R_0 + tR_1 is generally not orthogonal, so it shrinks and skews the model. Slerp (spherical linear interpolation) moves along the great circle between two unit quaternions at constant angular speed:

slerp⁡(q0,q1,t)=sin⁡((1−t)Ω) q0+sin⁡(tΩ) q1sin⁡Ω,cos⁡Ω=q0⋅q1\operatorname{slerp}(q_0, q_1, t) = \frac{\sin((1 - t)\Omega)\, q_0 + \sin(t\Omega)\, q_1}{\sin \Omega}, \qquad \cos \Omega = q_0 \cdot q_1

If q0⋅q1<0q_0 \cdot q_1 < 0, negate q1q_1 first so the blend takes the short way round. See Slerp.

python · try it yourself
import numpy as np

def to_matrix(q):
    w, x, y, z = q
    return np.array([[1 - 2*(y*y + z*z), 2*(x*y - w*z), 2*(x*z + w*y)],
                     [2*(x*y + w*z), 1 - 2*(x*x + z*z), 2*(y*z - w*x)],
                     [2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x*x + y*y)]])
def slerp(q0, q1, t):
    d = float(q0 @ q1)
    if d < 0: q1, d = -q1, -d
    om = np.arccos(min(d, 1.0))
    return (np.sin((1 - t) * om) * q0 + np.sin(t * om) * q1) / np.sin(om)

q0 = np.array([1.0, 0, 0, 0])                                  # identity
q1 = np.array([np.cos(np.radians(80)), 0, 0, np.sin(np.radians(80))])   # 160° about z
R0, R1 = to_matrix(q0), to_matrix(q1)
for t in (0.25, 0.5, 0.75):
    L = (1 - t) * R0 + t * R1
    S = to_matrix(slerp(q0, q1, t))
    ang = np.degrees(np.arctan2(S[1, 0], S[0, 0]))
    print(f"t={t}: lerped matrix det={np.linalg.det(L):.4f}  |L e1|={np.linalg.norm(L[:, 0]):.4f}   "
          f"slerp det={np.linalg.det(S):.4f} angle={ang:.1f}°")
t=0.25: lerped matrix det=0.2726  |L e1|=0.5221   slerp det=1.0000 angle=40.0°
t=0.5: lerped matrix det=0.0302  |L e1|=0.1736   slerp det=1.0000 angle=80.0°
t=0.75: lerped matrix det=0.2726  |L e1|=0.5221   slerp det=1.0000 angle=120.0°

Halfway between the identity and a 160° turn, the lerped matrix has squashed the model to almost nothing (det⁡≈0.03\det \approx 0.03), while slerp gives a clean 80° rotation.

Costs and practice

Task Matrix Quaternion
storage 9 floats 4 floats
compose two rotations 27 multiplies 16 multiplies
rotate one vector 9 multiplies about 15 (or convert to a matrix once)
fix numerical drift re-orthonormalize (Gram-Schmidt) divide by its length
interpolate not directly slerp / nlerp

So engines store orientations as quaternions (Unity's Quaternion, Unreal's FQuat, Three.js Quaternion), expose Euler angles in the editor, and convert to a 4×44 \times 4 matrix when it is time to render.

Exercises

Exercise 1: Quaternion for a turn

Write the unit quaternion for a 180° rotation about the yy-axis.

Answer

q=0+0i+1j+0kq = 0 + 0i + 1j + 0k (and −q-q is the same rotation).

Solution

cos⁡(90∘)=0\cos(90^\circ) = 0 and sin⁡(90∘)=1\sin(90^\circ) = 1, so q=(0,0,1,0)q = (0, 0, 1, 0) in (w,x,y,z)(w, x, y, z) order.

Exercise 2: Lost degree of freedom

With R=Ry(yaw)⋅Rx(pitch)⋅Rz(roll)R = R_y(\text{yaw}) \cdot R_x(\text{pitch}) \cdot R_z(\text{roll}) and pitch=90∘\text{pitch} = 90^\circ, which other Euler triple gives the same matrix as (yaw,roll)=(10∘,40∘)(\text{yaw}, \text{roll}) = (10^\circ, 40^\circ)?

Answer

Any (10∘+s,40∘+s)(10^\circ + s, 40^\circ + s), for example (0∘,30∘)(0^\circ, 30^\circ) or (40∘,70∘)(40^\circ, 70^\circ).

Solution

Conjugating a rotation moves its axis: Rx(90∘)⋅Rz(b)⋅Rx(90∘)−1R_x(90^\circ) \cdot R_z(b) \cdot R_x(90^\circ)^{-1} is the rotation by bb about Rx(90∘)ez=(0,−1,0)R_x(90^\circ)\mathbf{e}_z = (0, -1, 0), which is Ry(−b)R_y(-b). So

Ry(a)⋅Rx(90∘)⋅Rz(b)=Ry(a)⋅Ry(−b)⋅Rx(90∘)=Ry(a−b)⋅Rx(90∘)R_y(a) \cdot R_x(90^\circ) \cdot R_z(b) = R_y(a) \cdot R_y(-b) \cdot R_x(90^\circ) = R_y(a - b) \cdot R_x(90^\circ)

Only yaw−roll=−30∘\text{yaw} - \text{roll} = -30^\circ matters, so adding the same ss to both angles gives the same matrix, exactly what the lesson's code found.

Exercise 3: Double cover

Show that qq and −q-q rotate every vector the same way.

Answer

(−q)v(−q)∗=qvq∗(-q)\mathbf{v}(-q)^* = q\mathbf{v}q^*.

Solution

Conjugation is linear, so (−q)∗=−q∗(-q)^* = -q^*, and the two minus signs cancel: (−q)v(−q∗)=qvq∗(-q)\mathbf{v}(-q^*) = q\mathbf{v}q^*.

Exercise 4: Slerp halfway (code)

Slerp halfway between a 0° and a 90° rotation about xx, and check that the result rotates (0,1,0)(0, 1, 0) to (0,cos⁡45∘,sin⁡45∘)(0, \cos 45^\circ, \sin 45^\circ).

Answer

q=(cos⁡22.5∘,sin⁡22.5∘,0,0)≈(0.9239,0.3827,0,0)q = (\cos 22.5^\circ, \sin 22.5^\circ, 0, 0) \approx (0.9239, 0.3827, 0, 0), which maps (0,1,0)(0, 1, 0) to (0,0.7071,0.7071)(0, 0.7071, 0.7071).

Solution

The angle between the quaternions is Ω=45∘\Omega = 45^\circ (half of 90°), so the halfway quaternion is at 22.5° on the great circle, a 45° rotation.

python · try it yourself
import numpy as np
q0 = np.array([1.0, 0, 0, 0]); q1 = np.array([np.cos(np.pi / 4), np.sin(np.pi / 4), 0, 0])
om = np.arccos(q0 @ q1)
q = (np.sin(0.5 * om) * q0 + np.sin(0.5 * om) * q1) / np.sin(om)
w, x = q[0], q[1]
Rx = np.array([[1, 0, 0], [0, 1 - 2*x*x, -2*w*x], [0, 2*w*x, 1 - 2*x*x]])
print(np.round(q, 4), np.round(Rx @ [0, 1, 0], 4))
[0.9239 0.3827 0.     0.    ] [0.     0.7071 0.7071]

Test yourself

What is gimbal lock?

  1. A rotation matrix with determinant 0
  2. Losing one degree of freedom in an Euler-angle parametrization when two axes line up
  3. A bug in quaternion multiplication
  4. The double cover q≡−qq \equiv -q

Why is linearly interpolating two rotation matrices a bad idea?

  1. It is too slow
  2. The result is generally not orthogonal, so it scales and skews
  3. It always gives the identity
  4. Matrices cannot be added

A unit quaternion for a rotation of θ\theta about axis n\mathbf{n} has scalar part…

  1. cos⁡θ\cos \theta
  2. sin⁡θ\sin \theta
  3. cos⁡(θ/2)\cos(\theta/2)
  4. θ\theta