ProjekinAja. Robotics Stage 1 · Foundations Lesson 1.3
● Stage 1 · Lesson 1.3

Rotation Representations: Matrices, Euler Angles, and Quaternions

Three ways to represent rotation — each with a different failure mode. Pick the wrong one at the wrong time and your robot locks up.

⏱ ~22 min read 🧠 Core mathematics ⚠ Gimbal lock deep dive

🎯 By the end you'll understand

Why rotation matrices in SO(3) encode orthonormality as a physical invariant, not just a convention. How Euler angles construct any orientation from three sequential rotations — and the precise geometric mechanism by which ZYX Euler angles hit singularity at ±90° pitch. Why unit quaternions avoid that singularity, what the Hamilton product does physically, and how SLERP produces uniform angular velocity that LERP cannot. Which representation to use at runtime and which to use in configuration files. And how to recognize gimbal lock in a live system from symptoms, not from reading source code.

KEY INSIGHTThree representations, three failure modes — choose deliberately

There is no universally correct way to represent rotation. There are three representations, each optimal for a different task — and each carrying a specific failure mode the other two do not share.

Coordinate frames (Lesson 1.2) tell you where things are. But robots also rotate, and rotation is where most engineers make their first serious mistake. A rotation matrix is unambiguous but expensive; Euler angles are human-readable but singular; quaternions are compact, singularity-free, and interpolable but unintuitive. The mistake is not using one representation everywhere. The smart move is knowing which to use where, and knowing what breaks when you use the wrong one.

🔑 The invariant that governs everything

Every valid 3D rotation can be represented as a rotation by some angle θ around some unit axis k. This is Euler's rotation theorem, and it is not a convention — it is a theorem about the structure of three-dimensional space. Any rotation matrix, any Euler-angle triple, and any unit quaternion that represents a valid rotation is ultimately encoding this same (θ, k) pair. The three representations differ in how they encode it, what you can efficiently do with it, and where the encoding breaks.

CORE CONCEPTSO(3) rotation matrices: the unambiguous baseline

A rotation matrix R is a 3×3 real matrix that maps a vector expressed in one frame to the same vector expressed in a rotated frame. For it to represent a pure rotation (no scaling, no reflection), it must satisfy two constraints:

Constraint 1: Orthonormality R ᵀ R = I columns are mutually orthogonal each column has unit length encoding: the 3 axes of the rotated frame expressed in the parent frame Constraint 2: Handedness det( R ) = +1 rules out improper rotations (reflections have det = −1) guarantees right-handed frame preserved after rotation
The two defining constraints of SO(3). Together they enforce that R encodes a pure rotation: no stretching, no reflection, preserves the right-hand rule. Any 3×3 matrix satisfying both is a valid rotation matrix.

The columns of R tell you exactly where the child frame's x, y, z axes point in the parent frame. If frame B is rotated 90° around the parent's z-axis relative to frame A, then B's x-axis points along A's y-axis, B's y-axis points along A's negative x-axis, and B's z-axis is unchanged:

rotation_90z.pynumpy · SO(3)
import numpy as np

# 90° rotation around Z: B's x-axis → A's y; B's y-axis → A's -x
R_AB = np.array([
    [ 0, -1,  0],   # col 0: where B's x-axis goes in A
    [ 1,  0,  0],   # col 1: where B's y-axis goes in A
    [ 0,  0,  1],   # col 2: where B's z-axis goes in A
], dtype=float)

# verify SO(3): R^T R == I and det == +1
print(np.allclose(R_AB.T @ R_AB, np.eye(3)))  # True
print(np.round(np.linalg.det(R_AB), 6))        # 1.0

# express vector v_B in frame A: R_AB @ v_B
v_B = np.array([1, 0, 0])  # x-unit in B
v_A = R_AB @ v_B           # → [0, 1, 0]: points along A's y — correct

Why the orthonormality constraint matters physically: it encodes the fact that a rotation preserves lengths and angles. If you distort R by floating-point drift over many matrix multiplications — a real problem in long-running systems — you accumulate scale and shear error. The composed transform no longer represents a pure rotation; vectors "grow" or "shrink" under repeated application. The fix in production code is periodic re-orthonormalization (Gram-Schmidt or SVD), or switching to quaternions which have an easier normalization path.

💡 9 numbers, 3 degrees of freedom

A rotation in 3D has 3 degrees of freedom (DOF). Yet a rotation matrix stores 9 numbers. The 6 orthonormality constraints (3 unit-length + 3 orthogonality) reduce those 9 to the correct 3. This redundancy is both the strength (unambiguous, easy to compose) and the cost (9× memory, numerical drift) of the matrix representation. Every other representation tries to trim closer to the 3-DOF minimum — and pays for it with its own failure mode.

Composing rotations: to rotate from frame C to frame A via an intermediate frame B, left-multiply: R_AC = R_AB @ R_BC. Order matters — matrix multiplication is not commutative. This is how TF2 chains transform lookups: each edge in the TF tree is a rotation (and translation), and path queries compose them in order from leaf to root.

CORE CONCEPTEuler angles and ZYX convention

Euler angles decompose a rotation into three sequential rotations around coordinate axes. The decomposition is intuitive for humans — "yaw 30°, then pitch 20°, then roll 5°" — but the choice of axes and order creates a family of 12 conventions (6 proper Euler, 6 Tait-Bryan). Robotics and aerospace almost universally use the ZYX Tait-Bryan convention (also called roll-pitch-yaw or RPY), because it aligns naturally with how mobile robots move: yaw is the heading change (rotate around world-up Z), pitch is the nose-up/down tilt (rotate around new Y), roll is the lean sideways (rotate around newest X).

Step 1 · Yaw rotate ψ around Z Z x x' ψ Step 2 · Pitch rotate θ around Y' (new Y) Y' x' x'' θ Step 3 · Roll rotate φ around X'' (new X) X'' z' z'' φ
ZYX decomposition. Each rotation is about the current (body-fixed) axes after previous rotations — not the original world axes. The three angles are: ψ (psi) = yaw around Z, θ (theta) = pitch around Y', φ (phi) = roll around X''. The full rotation matrix is R = R_z(ψ) · R_y(θ) · R_x(φ).

The rotation matrix for the ZYX convention is the product:

euler_to_matrix.pynumpy · ZYX RPY
import numpy as np

def Rz(psi):
    c, s = np.cos(psi), np.sin(psi)
    return np.array([[c, -s, 0],[s, c, 0],[0, 0, 1]])

def Ry(theta):
    c, s = np.cos(theta), np.sin(theta)
    return np.array([[c, 0, s],[0, 1, 0],[-s, 0, c]])

def Rx(phi):
    c, s = np.cos(phi), np.sin(phi)
    return np.array([[1, 0, 0],[0, c, -s],[0, s, c]])

def rpy_to_R(roll, pitch, yaw):
    # ZYX: first yaw, then pitch, then roll (intrinsic rotations)
    return Rz(yaw) @ Ry(pitch) @ Rx(roll)

# Example: FollowBot camera pitched down 5° to view floor in front
R = rpy_to_R(roll=0, pitch=np.deg2rad(-5), yaw=0)
print(R.round(3))

Euler angles are popular in configuration files (ROS URDF uses RPY, nav2 uses yaw for 2D poses) because a human can read "pitch -5°" and picture it. But this human-readability comes with a structural cost that becomes a runtime failure.

HOW IT WORKSGimbal lock: the geometric mechanism

Gimbal lock is not a software bug. It is a geometric consequence of the Euler angle parameterization. Understanding the mechanism — not just memorizing "avoid ±90° pitch" — is what lets you diagnose it in the field.

In ZYX convention, the full rotation matrix R_ZYX(ψ, θ, φ) is:

gimbal_lock_derivation.pysymbolic · what collapses at θ = ±90°
# Full R_ZYX product (abbreviated — key structure shown)
#
# R = [[cy·cψ,  cy·sψ·sφ - sθ·cφ,  cy·sψ·cφ + sθ·sφ],
#      [sθ·cψ,  sθ·sψ·sφ + cy·cφ,  sθ·sψ·cφ - cy·sφ],   ← NON-degenerate case
#      [-sθ,    cθ·sφ,              cθ·cφ             ]]
#
# At θ = +90° (pitch 90° nose-up): cθ=0, sθ=+1
# Row 2 (bottom): [-1, 0, 0]  → θ is fixed at +90°
# Rows 0, 1 simplify to pure sums/differences of (ψ+φ).
#
# The matrix now only depends on (ψ + φ), not ψ and φ independently.
# Two DOF have collapsed into one: yaw and roll are indistinguishable.
#
# Symptom: trying to command 'roll=10°, yaw=0°' and 'roll=0°, yaw=10°'
#          produces IDENTICAL rotation matrices. The robot cannot separate them.

import numpy as np

def rpy_to_R(r, p, y):
    cr,sr = np.cos(r),np.sin(r)
    cp,sp = np.cos(p),np.sin(p)
    cy,sy = np.cos(y),np.sin(y)
    return np.array([
        [cy*cp, cy*sp*sr-sy*cr, cy*sp*cr+sy*sr],
        [sy*cp, sy*sp*sr+cy*cr, sy*sp*cr-cy*sr],
        [  -sp,          cp*sr,          cp*cr]
    ])

# At pitch = 90°, roll=10°,yaw=0° vs roll=0°,yaw=10° → same matrix
R1 = rpy_to_R(np.deg2rad(10), np.pi/2, 0)
R2 = rpy_to_R(          0,  np.pi/2, np.deg2rad(10))
print(np.allclose(R1, R2))  # True — gimbal lock: two states → same R
⚠ Gimbal lock is not rare in robotics

A camera mounted on a pan-tilt unit that looks straight up or straight down hits gimbal lock. An aerial drone that flips to vertical for acrobatics hits it. A robotic arm reaching directly overhead pitches its wrist joint to ±90°. In each case, the Euler angle parameterization loses one DOF, the Jacobian becomes rank-deficient, and any numerical solver using Euler angles will either hang, spike, or produce NaN. The symptom in RViz: a transform that was animated smoothly suddenly snaps or tumbles when crossing ±90° pitch.

Diagnosing gimbal lock from symptoms — not source code: Look for three specific signatures. First, two independent control inputs (say, yaw command and roll command) produce the same output motion — they have become coupled. Second, the angular velocity estimate spikes to implausibly large values near ±90° pitch (the inverse Euler Jacobian diverges). Third, the behavior is repeatable and pitch-dependent: it goes away as soon as pitch leaves ±90°. If you see these three together, do not look at the PID, do not look at the URDF joint limits — look at the rotation parameterization in the state estimator or controller.

CORE CONCEPTUnit quaternions: compact, singularity-free, interpolable

A quaternion extends the complex number idea to four dimensions: q = w + xi + yj + zk, where i, j, k are imaginary units satisfying i² = j² = k² = ijk = −1 (Hamilton's rule). For rotation, we use unit quaternions: those with ||q|| = w² + x² + y² + z² = 1. The unit quaternion sphere S³ is a double cover of SO(3): q and −q represent the same rotation. This doubling is the quaternion's only quirk, and it is manageable.

Encoding a rotation via (axis, angle): to rotate by angle θ around unit axis k = (kx, ky, kz):

axis_angle_to_quat.pynumpy · Hamilton convention
import numpy as np

def axis_angle_to_quat(axis, angle_rad):
    """Returns (w, x, y, z) unit quaternion. axis must be a unit vector."""
    ha = angle_rad / 2.0
    w = np.cos(ha)
    x, y, z = np.sin(ha) * np.array(axis)
    return np.array([w, x, y, z])

# 90° around Z (same as R_90z above)
q = axis_angle_to_quat([0, 0, 1], np.pi/2)
# q ≈ [0.7071, 0, 0, 0.7071] — w=cos(45°), z=sin(45°)
print(q.round(4))  # [0.7071, 0.    , 0.    , 0.7071]

# Normalize after any arithmetic (fp drift):
q = q / np.linalg.norm(q)

The Hamilton product — composing rotations: to compose rotation q₁ followed by q₂, multiply: q_total = q₂ ⊗ q₁. The Hamilton product of two quaternions q_a = (wa, xa, ya, za) and q_b = (wb, xb, yb, zb) is:

hamilton_product.pynumpy · quaternion composition
def quat_mul(q1, q2):
    """Hamilton product q1 ⊗ q2. Both are (w,x,y,z) arrays."""
    w1,x1,y1,z1 = q1
    w2,x2,y2,z2 = q2
    return np.array([
        w1*w2 - x1*x2 - y1*y2 - z1*z2,   # w
        w1*x2 + x1*w2 + y1*z2 - z1*y2,   # x
        w1*y2 - x1*z2 + y1*w2 + z1*x2,   # y
        w1*z2 + x1*y2 - y1*x2 + z1*w2    # z
    ])

# In ROS 2 / tf2: use tf2.transformations or scipy.spatial.transform
from scipy.spatial.transform import Rotation
r1 = Rotation.from_euler('z', 90, degrees=True)
r2 = Rotation.from_euler('y', 45, degrees=True)
r_total = r2 * r1   # r2 applied after r1 (left-multiply)
print(r_total.as_quat())  # scipy uses (x,y,z,w) order — note convention

SLERP — Spherical Linear Interpolation: to smoothly animate between two orientations q₀ and q₁, SLERP traces the shortest arc on the unit quaternion sphere S³:

slerp.pypure numpy · t ∈ [0,1]
def slerp(q0, q1, t):
    """Spherical linear interpolation; t=0 → q0, t=1 → q1."""
    dot = np.clip(np.dot(q0, q1), -1.0, 1.0)
    # take the shorter arc (q and -q are the same rotation)
    if dot < 0:
        q1, dot = -q1, -dot
    if dot > 0.9995:          # nearly identical: fall back to NLERP
        return (q0 + t*(q1-q0)) / np.linalg.norm(q0 + t*(q1-q0))
    omega = np.arccos(dot)   # half the total rotation angle
    return (np.sin((1-t)*omega)/np.sin(omega))*q0 \
         + (np.sin(   t *omega)/np.sin(omega))*q1

SLERP is used in animation, in trajectory generators, and in any filter that needs to blend two orientation estimates smoothly. LERP (naive linear interpolation of quaternion components) is cheaper but wrong: it does not travel along the great circle, so the interpolated rotation travels at non-uniform angular speed and the quaternion must be renormalized at every step — losing the benefit of simplicity without gaining correctness.

📖 ROS 2 quaternion convention

ROS 2 (and TF2) use the (x, y, z, w) component order — w last. scipy's as_quat() also returns (x, y, z, w). The axis-angle formula above uses (w, x, y, z) — w first (Hamilton convention). Check the order every time you cross a library boundary. Mixing conventions produces rotations that appear to work in simulation (the magnitudes are similar) but are wrong by up to 180°. This is a real, recurring bug in robotics code.

SEE ITRotation explorer

Compose three Euler-angle rotations with the sliders and watch the quaternion, rotation matrix, and a SLERP/LERP comparison update live. The consequential decision: drag the pitch slider to ±90° and observe what happens to the quaternion and what happens to the matrix — gimbal lock in action. Then switch to the SLERP panel and see why naive LERP of quaternion components produces non-uniform angular speed.

⚙ Interactive · Rotation Explorer

Drag sliders to compose a ZYX rotation. Drive pitch to ±90° to trigger gimbal lock. Switch to SLERP tab to compare interpolation quality.

⚠ Gimbal lock! Pitch = ±90° — yaw and roll control the same DOF.
The matrix row 2 = [-1/+1, 0, 0]. Yaw and roll are indistinguishable. The quaternion is still valid — this is the key advantage.
Quaternion (w, x, y, z) — ROS uses (x,y,z,w)
w=1.0000 x=0.0000 y=0.0000 z=0.0000
Rotation matrix R (3×3)
[ 1.000 0.000 0.000 ]
[ 0.000 1.000 0.000 ]
[ 0.000 0.000 1.000 ]
Axis-angle equivalent
θ = 0.0° axis = (0.000, 0.000, 1.000)
Rotated frame axes (isometric projection) X Y Z
Live isometric projection of the rotated frame. X (stage color), Y (green), Z (gold). At gimbal lock the frame still renders correctly — the quaternion representation has no singularity.

Interpolating between two orientations: SLERP travels along the geodesic (great circle on S³) at constant angular velocity. LERP travels along a chord, requiring renormalization, producing non-uniform angular speed. Choose which pair of orientations to interpolate:

The key insight from the Compose pane: at pitch = ±90°, the quaternion remains a perfectly valid, non-degenerate unit vector — w² + x² + y² + z² = 1 is unchanged. The singularity is a property of the Euler angle parameterization, not of the underlying rotation. This is why quaternions are the runtime representation of choice in every production robotics stack.

IN PRACTICEConversion paths and the runtime recommendation

Representation Storage Singularity Best for Avoid when
Rotation matrix (SO(3)) 9 floats (6 redundant) None Composing many rotations; linear algebra (Jacobians, SVD) Memory-constrained systems; logging (verbose)
Euler angles (ZYX/RPY) 3 floats (minimal, but degenerate) Gimbal lock at ±90° pitch Configuration files, human-readable URDF/YAML; 2D yaw-only systems (mobile bases) Runtime state representation; any system that crosses ±90° pitch
Unit quaternion 4 floats (1 redundant) None (double cover only) Runtime state, EKF orientation state, TF2 transforms, interpolation (SLERP) Config files read by humans; when (q, −q) ambiguity must be avoided (e.g. averaging)
Axis-angle 4 floats or 3 (angle*axis) Undefined at 0° rotation Compact logging; Lie algebra operations; angular velocity integration Runtime composition (no closed-form Hamilton product equivalent)

Conversion paths — always go through quaternion as intermediate:

1

Euler → Quaternion (config file to runtime)

Use scipy.spatial.transform.Rotation.from_euler('zyx', [yaw, pitch, roll]) or tf_transformations.quaternion_from_euler(roll, pitch, yaw) in ROS 2. Do this conversion once at startup when reading URDF RPY values. Never iterate with Euler angles at runtime — you will eventually cross a singularity.

2

Quaternion → Matrix (for linear algebra)

Closed-form, no trig needed: R = q.as_matrix() in scipy. Use when you need to multiply vectors or chain with a translation (homogeneous transform, as in Lesson 1.2). The matrix is exact; the conversion from quaternion to matrix costs 12 multiplications.

3

Matrix → Quaternion (after matrix accumulation)

Use Shepperd's method (or SVD for numerical stability). Required when you accumulate rotations via matrix multiplication (e.g., in an arm FK chain) and need to output a quaternion for TF2. Re-normalize at each step to prevent drift: q = q / np.linalg.norm(q).

4

Quaternion → Euler (display only)

Use R.as_euler('zyx', degrees=True). Never use the output for further computation — you've re-introduced the singularity. This conversion is valid only for logging, debugging overlays in RViz, or writing values back to a human-readable config. If you find yourself converting to Euler for anything other than display, reconsider the design.

🔑 The runtime rule

In any ROS 2 node that runs during robot operation: store orientations as quaternions (or rotation matrices if you need linear algebra), publish quaternions to TF2, and convert to Euler only for display. Read Euler from URDF and config files but convert immediately at node startup. If you find an orientation stored as three floats (roll/pitch/yaw) in a message being passed between runtime nodes, flag it as a design defect.

FOLLOWBOTTF tree rotations in practice

FollowBot's TF tree (map → odom → base_link → laser → camera) was introduced in Lesson 1.2. Every edge in that tree is a full SE(3) transform — a rotation plus a translation. The rotations in FollowBot's URDF are defined in RPY (because that is what URDF requires), but at runtime TF2 converts every transform to a quaternion-based representation before broadcasting. Here is what that looks like for the camera joint:

followbot_camera.urdfURDF · camera joint RPY
<!-- URDF: camera mounted 5 cm forward, 20 cm up, pitched −5° downward -->
<joint name="camera_joint" type="fixed">
  <parent link="base_link"/>
  <child  link="camera_link"/>
  <origin xyz="0.05 0 0.20"
           rpy="0 -0.0873 0"/>  <!-- rpy = roll pitch yaw; −0.0873 rad = −5° -->
</joint>

When robot_state_publisher reads this URDF, it converts the RPY values to a quaternion and publishes the base_link → camera_link transform as a geometry_msgs/TransformStamped with a quaternion orientation field. The RPY in the file is configuration; the quaternion on the TF2 bus is the runtime state.

read_camera_tf.pyrclpy · look up TF2 in Python
import rclpy
from rclpy.node import Node
from tf2_ros import Buffer, TransformListener

class TFReader(Node):
    def __init__(self):
        super().__init__('tf_reader')
        self.buf = Buffer()
        self.listener = TransformListener(self.buf, self)
        self.create_timer(1.0, self.read)

    def read(self):
        try:
            tf = self.buf.lookup_transform(
                'base_link', 'camera_link',
                rclpy.time.Time()
            )
            q = tf.transform.rotation
            # TF2 returns (x, y, z, w) — NOT (w, x, y, z)
            self.get_logger().info(
                f'camera q: x={q.x:.4f} y={q.y:.4f} z={q.z:.4f} w={q.w:.4f}'
            )
        except Exception as e:
            self.get_logger().warn(str(e))

The output will be approximately: x=0.0000, y=−0.0436, z=0.0000, w=0.9990 — the quaternion for a 5° pitch-down rotation. Now consider what happens if FollowBot's 6-DOF arm swings overhead. If you track the arm's end-effector orientation using Euler angles, the pitch will approach 90° during the overhead trajectory. The EKF or IK solver using Euler angles will become ill-conditioned at that point. The fix — use quaternions in the arm controller throughout, convert to RPY only for joint-space display.

🔑 Stage 1 milestone: TF tree rotation audit

Before leaving Stage 1, audit every joint in FollowBot's URDF. For each fixed joint, verify that the RPY values avoid ±90° pitch in steady-state configuration (a camera pointed straight down or arm raised overhead at startup creates gimbal lock at the first EKF update). For revolute joints (like the arm), verify that the joint limits in the URDF exclude ±90° pitch if any downstream node uses Euler angles for that joint's orientation. Document which nodes use quaternions (all ROS 2 runtime nodes should) and which receive RPY (URDF, nav2 initial pose — these are startup configs, not runtime state).

WEAKNESSWhere this bites

✗ Publishing Euler angles on a ROS 2 topic between runtime nodes

The most common rotation bug in robotics code review: a custom message type with three floats (roll, pitch, yaw) being published between nodes at runtime. This looks harmless — it did not fail in testing because the test trajectory never reached ±90° pitch. In deployment, when the arm reaches overhead or the camera tilts fully down, the receiver node's conversion back to quaternion hits the singularity. The fix is architecturally trivial: use geometry_msgs/Quaternion in the message. The refusal to fix it ("it works in testing") is the actual bug.

✗ Mixing quaternion conventions across library boundaries

ROS 2 / TF2 uses (x, y, z, w) — w last. scipy uses (x, y, z, w) by default. Eigen uses (w, x, y, z) — w first. The manual "Hamilton convention" is (w, x, y, z). A quaternion passed from a scipy computation into a manual Hamilton-product function with the convention swapped produces a rotation that is wrong by up to 180°. In simulation the error might be small enough to pass integration tests; on hardware it can command a 180° rotation. Convention errors do not raise exceptions. They manifest as mysterious pose offsets that are stable but wrong. Fix: define a single internal convention per codebase, document it in a comment at the top of every file that does quaternion arithmetic, and write a unit test that verifies a known rotation at the boundary.

✗ Accumulating small rotations via quaternion addition (not multiplication)

When integrating angular velocity to propagate orientation (common in EKFs), the temptation is to add a small quaternion delta: q_new = q + ω·Δt. This is wrong in two ways. First, quaternion addition does not produce a valid rotation (the result is not on S³). Second, even after renormalization, the result is only correct to first order in Δt and accumulates error. The correct integration is: q_new = q ⊗ exp(ω·Δt/2), where exp is the quaternion exponential map. For small Δt (small angular steps), the first-order approximation q_new ≈ q ⊗ (1, ω·Δt/2) is widely used and acceptable if Δt ≤ 0.02 s (50 Hz). Beyond that, use the closed-form axis-angle integration.

KEY INSIGHTHow this connects

  • Coordinate Frames and Homogeneous Transforms (1.2) — this lesson extends that foundation: the rotation block R of the 4×4 homogeneous transform is precisely the SO(3) matrix developed here. Every transform in FollowBot's TF tree contains a quaternion that maps through the conversions covered above.
  • ROS 2 Architecture: Nodes, Topics, Services, and Actions (1.4) — TF2 publishes quaternion-based transforms on the /tf topic. Understanding the quaternion representation is required before the TF2 lookup API makes sense. The (x, y, z, w) convention in geometry_msgs is defined in the ROS 2 standard interfaces, not an arbitrary choice.

Rotation representations appear in every subsequent stage. Stage 2 (Kinematics) derives the Jacobian of a rotation matrix and hits the singularity again — this time as a kinematic singularity in the arm workspace. Stage 4 (State Estimation) stores the robot's orientation as a quaternion in the EKF state vector and integrates it using the exponential map. Stage 5 (SLAM) uses rotation matrices in point cloud registration. Every time you see an orientation in this course, ask: which representation is being used here, and could the singularity bite at this operating point?

GLOSSARYKey terms introduced

SO(3)
The special orthogonal group in three dimensions: the set of all 3×3 real matrices R with Rᵀ R = I and det(R) = +1. The mathematical structure of pure rotations in 3D space. "Special" means det = +1 (no reflections); "orthogonal" means Rᵀ R = I (no stretching).
ZYX Euler angles (RPY)
A decomposition of any 3D rotation into three sequential rotations: first around world Z (yaw ψ), then around new Y (pitch θ), then around newest X (roll φ). Used in URDF and nav2 initial poses. Singular at pitch ±90° (gimbal lock). Full name: Tait-Bryan ZYX angles, colloquially roll-pitch-yaw.
Gimbal lock
The loss of one rotational degree of freedom that occurs when the middle (pitch) Euler angle reaches ±90°. At this configuration the first and third rotation axes become collinear, reducing the three-angle parameterization to an effective two-angle parameterization. Not a software bug — a geometric consequence of the Euler angle representation.
Unit quaternion
A quaternion q = w + xi + yj + zk with ||q|| = 1. Encodes a rotation by angle θ around unit axis k as: w = cos(θ/2), (x,y,z) = sin(θ/2)·k. Has no gimbal-lock singularity. q and −q represent the same rotation (double cover of SO(3)). The preferred runtime rotation representation in ROS 2.
Hamilton product
The composition law for quaternions: q₂ ⊗ q₁ represents rotation q₁ followed by rotation q₂. Derived from the rule i² = j² = k² = ijk = −1. Not commutative (same as matrix multiplication for rotations). Used in TF2 transform chaining and EKF orientation propagation.
SLERP
Spherical Linear Interpolation. Traces the geodesic (shortest arc) on the unit quaternion sphere S³ between two orientations, producing constant angular velocity. The correct method for blending orientations in animation, trajectory generation, and filter state interpolation. Contrast with LERP, which traverses a chord and produces non-uniform angular velocity.
Double cover
The property that both q and −q represent the same physical rotation. Mathematically, the map from unit quaternions S³ → SO(3) is 2-to-1. Practically: when interpolating or averaging quaternions, always check sign consistency (dot product > 0) to avoid taking the long arc around S³ instead of the short one.
Euler's rotation theorem
Any sequence of rotations in 3D space is equivalent to a single rotation by some angle θ around some fixed axis k. Guarantees that the axis-angle, matrix, and quaternion representations are all encoding the same underlying geometric object. A theorem, not a convention.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1A rotation matrix has 9 entries but a rotation in 3D has only 3 degrees of freedom. What are the 6 constraints that account for the redundancy, and what does each mean physically?›

The 6 constraints come from the condition Rᵀ R = I. This 3×3 symmetric equation gives 6 independent scalar equations: 3 unit-length constraints (the diagonal entries of Rᵀ R = I: each column of R has length 1 — the three axes of the rotated frame are unit vectors) and 3 orthogonality constraints (the off-diagonal entries: the three axes are mutually perpendicular). The seventh constraint, det(R) = +1, is not independent once Rᵀ R = I holds — it follows except for the sign, which distinguishes proper rotations (det = +1) from improper ones (det = −1, reflections). Physically: unit length ensures rotations preserve distances; orthogonality ensures they preserve angles; det = +1 ensures they preserve handedness (right-hand rule).

2Explain geometrically why gimbal lock occurs at pitch = ±90° in ZYX Euler angles. What exactly collapses?›

In ZYX convention: first rotate around world Z (yaw), then around the new Y axis (pitch), then around the newest X axis (roll). When pitch = +90°, the "newest X axis" (roll axis) has been tilted by exactly 90° — it now coincides with the original world Z axis (yaw axis). Two physically distinct rotation axes — the yaw axis and the roll axis — have become the same axis. A yaw rotation and a roll rotation now produce identical physical motion. The three-angle parameterization has effectively reduced to two independent angles (only the sum ψ + φ appears in the matrix, not ψ and φ separately). One degree of freedom is lost: no matter what combination of yaw and roll you specify at pitch = 90°, you can only access a 2D family of orientations, not the full 3D family. The quaternion for this configuration is perfectly well-defined — the singularity is in the Euler angle coordinates, not in the rotation itself.

3Why is SLERP preferred over LERP for quaternion interpolation? What goes wrong with LERP?›

LERP interpolates quaternion components linearly: q(t) = (1−t)·q₀ + t·q₁. Two problems. First, the result is not on the unit quaternion sphere S³ — it must be renormalized at each step, adding cost and making the "simplicity" argument false. Second and more importantly, even after normalization, LERP does not travel along the great circle between q₀ and q₁. It follows a chord. This means the angular velocity is not constant: the orientation changes faster near the endpoints and slower near the midpoint (or vice versa, depending on the arc length). For animation this looks unnatural. For a trajectory generator feeding a controller, the non-constant angular velocity creates a time-varying disturbance that the control loop was not designed to handle. SLERP resolves both problems by directly parameterizing the arc: q(t) = sin((1−t)Ω)/sin(Ω) · q₀ + sin(tΩ)/sin(Ω) · q₁, where Ω is the half-angle between q₀ and q₁. The angular velocity is exactly constant, no renormalization is needed, and it degrades gracefully to normalized LERP when Ω → 0.

4FollowBot's RViz display shows the camera_link frame tumbling wildly when the head tilts down past vertical. The URDF has rpy="0 −1.5708 0" (−90° pitch) for the camera joint. What is happening and how do you fix it?›

The camera joint is configured at exactly −90° pitch in steady state — the gimbal lock angle. Even though the joint is fixed (not actuated), any downstream node that reads this transform and converts it to Euler angles for further computation will encounter the singularity. If robot_state_publisher adds small numerical noise (from floating-point arithmetic), the Euler recovery from the quaternion can return wildly varying yaw/roll values for nearly identical quaternions near this singularity. The fixes: (1) redesign the camera mount so the static pitch is not exactly ±90° — even −85° or −89° avoids the singularity; (2) if −90° is physically required, ensure every downstream node receives the quaternion directly from TF2 and never converts to Euler angles for intermediate computation. The TF2 quaternion for −90° pitch is exact and well-defined; the Euler conversion is what breaks. This is the practical reason the milestone audit asks you to check every URDF joint for steady-state ±90° pitch.

Next: ROS 2 architecture — nodes, topics, services, and actions →