Skip to the content
FixTheRobot Explore Robotics / UAV / Module 3 / M3-T4

UAV Systems Engineering · Module 3

M3-T4: Kalman Filter

A Kalman filter is a weighted average whose weights come from honest uncertainty: derive it, run it, and see the gain move.

  • Lesson 4 of 16
  • Sensor Fusion and State Estimation
  • Established engineering
  • About 7 minutes to read

Every estimator in this track, from the autopilot’s EKF2 to FAST-LIO2, is a Kalman filter or a close relative. The linear case is small enough to derive in full and run in twenty lines, and it explains the behaviour of the rest.

Learning objectives

After this lesson, you should be able to:

  • Write the predict and update equations of the Kalman filter and say what each term means.
  • Derive the Kalman gain as the minimiser of posterior variance in the scalar case.
  • Explain how QQ and RR set the trade-off between model and measurement.
  • Implement a constant-velocity filter and check its consistency.

Conceptual explanation

The Kalman filter keeps a Gaussian belief over the state: a mean x^\hat{x} and a covariance PP. It alternates two steps. Predict: push the belief through the motion model; uncertainty grows because the model is imperfect (process noise QQ). Update: when a measurement arrives, blend it with the prediction; uncertainty shrinks. The blend weight is the Kalman gain KK.

Kalman filter cycleThe filter alternates between predict, which propagates the state and grows the covariance using the motion model, and update, which corrects the state using a measurement and shrinks the covariance.PREDICTx⁻ = F x + B uP⁻ = F P Fᵀ + Q (grows) UPDATEx = x⁻ + K (z − H x⁻)P = (I − K H) P⁻ (shrinks) measurement z arrives
The predict–update cycle: covariance grows in predict and shrinks in update.

For linear models with Gaussian noise, it is the exact Bayesian posterior and the minimum-variance linear estimator. For non-linear ones (lesson M3-T5) it is an approximation.

Animation of three Kalman filters with different process noise on a vehicle that reverses direction. With too small a process noise the estimate is smooth but lags badly after the reversal; with a matched process noise it follows with a small lag; with too large a process noise it follows the noisy measurements closely and is jittery. A second chart shows the Kalman gain of each filter settling to a different value.
The ratio Q/R decides the Kalman gain: small QQ (trust the model) gives a low gain, a smooth but slow estimate; large QQ (trust the data) gives a high gain, a fast but noisy estimate. A one-dimensional constant-velocity model with measurement noise 1 m. Computed with the full Kalman equations. (Looping, about 6 seconds; drawn and computed for this course with illustrative values.)

Engineering intuition

In one dimension, the update is a weighted average of the prediction and the measurement, weighted by the inverse of their variances: whichever is more certain gets more weight. K=PK=P⁻/(PP⁻ + RR) is between 0 and 1: near 0 when the measurement is noisy (RR large) and near 1 when the prediction is poor (PP⁻ large). Tuning QQ is therefore a statement about how much you trust your model: a large QQ makes the filter nervous and responsive, a small QQ makes it smooth and slow to react to real changes.

Mathematical formulation

Model: xk=F xk−1+B uk+wkx_{k}=F\,x_{k-1}+B\,u_{k}+w_{k}, ww ~ NN(0, QQ); measurement zk=H xk+vkz_{k}=H\,x_{k}+v_{k}, vv ~ NN(0, RR).

Predict
x−=Fx+Bu,P−=FPF⊤+Q\mathbf x^{-} = \mathbf F\mathbf x + \mathbf B\mathbf u, \qquad \mathbf P^{-} = \mathbf F\mathbf P\mathbf F^{\top} + \mathbf Q
Update: innovation
y=z−Hx−\mathbf y = \mathbf z - \mathbf H\mathbf x^{-}
Update: innovation covariance
S=HP−H⊤+R\mathbf S = \mathbf H\mathbf P^{-}\mathbf H^{\top} + \mathbf R
Update: Kalman gain
K=P−H⊤S−1\mathbf K = \mathbf P^{-}\mathbf H^{\top}\mathbf S^{-1}
Update: state and covariance (Joseph form)
x=x−+Ky,P=(I−KH)P−(I−KH)⊤+KRK⊤\mathbf x = \mathbf x^{-} + \mathbf K\mathbf y, \qquad \mathbf P = (\mathbf I - \mathbf K\mathbf H)\mathbf P^{-}(\mathbf I - \mathbf K\mathbf H)^{\top} + \mathbf K\mathbf R\mathbf K^{\top}
xx, PP
state estimate and its covariance.
FF, BB, HH
state-transition, input and measurement matrices.
QQ, RR
process and measurement noise covariances.
yy, SS
innovation (residual) and its covariance: used for gating and consistency (lessons M3-T13, M3-T14).
KK
Kalman gain.

Scalar derivation

Combine a prior NN(xx⁻, PP⁻) and a measurement z=x+vz=x+v with variance RR. The posterior mean xx⁻ + KK(zz − xx⁻) has variance (1−K)2 P(1-K)^{2}\,P⁻ + K2 RK^{2}\,R. Setting the derivative with respect to KK to zero:

Optimal scalar gain
K=P−P−+RK = \frac{P^{-}}{P^{-} + R}
posterior variance=P−RP−+R=(1−K) P−<min⁡(P−,R)\text{posterior variance} = \frac{P^{-}R}{P^{-} + R} = (1 - K)\,P^{-} < \min(P^{-}, R)

The posterior is always more certain than either source. The Joseph form shown above is algebraically equal to (II − KH)PP⁻ but keeps PP symmetric positive definite under rounding error, so use it in real code.

Constant-velocity model

A common UAV tracking model
x=[pv],F=[1Δt01],H=[10]\mathbf x = \begin{bmatrix}p\\ v\end{bmatrix}, \qquad \mathbf F = \begin{bmatrix}1 & \Delta t\\ 0 & 1\end{bmatrix}, \qquad \mathbf H = \begin{bmatrix}1 & 0\end{bmatrix}
Q=q[Δt3/3Δt2/2Δt2/2Δt]\mathbf Q = q\begin{bmatrix}\Delta t^{3}/3 & \Delta t^{2}/2\\ \Delta t^{2}/2 & \Delta t\end{bmatrix}
Continuous white-noise acceleration with spectral density q.

Architecture and data flow

Sensor sample → timestamp and validity check → predict to the measurement time (never to “now”) → update → publish state and covariance. Getting the time of the prediction right is the most common implementation detail missed in practice: a measurement that is 80 ms old must be applied to the state as it was 80 ms ago, or an out-of-sequence strategy must be used.

Real-world UAV applications

  • GNSS-aided position and velocity tracking.
  • Altitude estimation from barometer and accelerometer.
  • Target tracking for follow-me and landing.
  • The core of the EKF inside PX4 and of every VIO and LIO system.

Implementation example

This runs as shown: a constant-velocity filter tracks a vehicle from noisy position measurements; it checks accuracy and that the filter’s covariance matches the actual error (statistical consistency).

import numpy as np
rng = np.random.default_rng(3)
dt, n = 0.1, 400
F = np.array([[1, dt], [0, 1]]); H = np.array([[1.0, 0.0]])
q = 0.5                                            # white acceleration spectral density
Q = q * np.array([[dt**3 / 3, dt**2 / 2], [dt**2 / 2, dt]])
R = np.array([[2.0**2]])                           # 2 m measurement sigma

# truth: accelerations are white noise with the SAME spectral density, so the model is correct
x_true = np.zeros((n, 2)); x = np.array([0.0, 5.0])
L = np.linalg.cholesky(Q)
for k in range(n):
    x = F @ x + L @ rng.standard_normal(2); x_true[k] = x
z = x_true[:, 0] + 2.0 * rng.standard_normal(n)

xh = np.array([0.0, 0.0]); P = np.diag([25.0, 25.0])
nees, err = [], []
for k in range(n):
    xh = F @ xh; P = F @ P @ F.T + Q                       # predict
    y = z[k] - H @ xh; S = H @ P @ H.T + R
    K = P @ H.T @ np.linalg.inv(S)
    xh = xh + (K @ y).ravel()
    I_KH = np.eye(2) - K @ H
    P = I_KH @ P @ I_KH.T + K @ R @ K.T                      # Joseph form
    e = xh - x_true[k]
    if k > 50: nees.append(e @ np.linalg.inv(P) @ e); err.append(e)
rms = np.sqrt(np.mean(np.array(err)[:, 0] ** 2))
print(f"position RMS error {rms:.2f} m (measurement sigma 2.0), mean NEES {np.mean(nees):.2f} (expected 2)")
assert rms < 2.0                                         # filtered estimate beats the raw measurement
assert 1.0 < np.mean(nees) < 3.2                         # consistent within sampling variability: 2 degrees of freedom
Constant-velocity Kalman filter with Joseph-form update and NEES consistency check.

Common engineering mistakes

Tuning Q and R by eye until it “looks smooth”

Smoothness hides lag. Use NIS and NEES (lessons M3-T14, M3-T15) to tune against statistics.

Updating with a stale measurement as if it were current

Predict to the measurement timestamp; handle delays explicitly.

Setting R from the datasheet and never checking it

Real noise is rarely white or Gaussian; estimate RR from logged data.

Using (I − KH)P instead of the Joseph form

Loses symmetry and can become indefinite after many updates.

Discretising Q incorrectly for variable Δt

QQ must scale with Δt\Delta t according to the noise model, not be a constant matrix.

Failure modes

Failure modes, symptoms and causes
Failure modeHow it shows upLikely cause
Filter lag on manoeuvresEstimate trails the truth during turnsQQ too small for the real acceleration changes
Jittery estimateOutput noisy, near the measurementsQQ too large or RR too small
Covariance collapseFilter ignores measurements after a whileQQ too small or missing; PP shrinks to near zero and KK to zero
Divergence after a bad measurementA single outlier pulls the state and it does not recoverNo gating of innovations

Debugging approach

  1. Plot the innovation yy and ±2S2\sqrt{S} bounds: about 95% of samples should fall inside and the sequence should look white.
  2. Compute NIS and NEES (simulation) and compare to their expected chi-square means.
  3. Verify the filter against a simulated truth where QQ and RR are known exactly, before trying real data.
  4. Check the sign and units of every matrix with a unit test of predict-only behaviour.

Practical exercises

  1. Derive the scalar gain and show posterior variance is below both prior variance and RR.
  2. Change qq in the example to 5 and then 0.05 while keeping the true qq at 0.5. Report NEES in both cases.
  3. Add acceleration to the state (three-state model) and compare the lag on a step in acceleration.
  4. Show that the filter reduces to a running average when F=1F=1, Q=0Q=0 and RR is constant.

Interview questions

Write an answer in your own words, then reveal the model answer. Nothing is sent anywhere.

Question 1

What does the Kalman gain do?

Model answer

It weights the correction by relative certainty: K=PK=P⁻H⊤H^{\top}(HP⁻H⊤+RH^{\top}+R)−1^{-1}, high when the prediction is uncertain or the measurement precise, low when the measurement is noisy.

Question 2

What happens if QQ is set too small?

Model answer

The filter becomes overconfident in its model: covariance shrinks, the gain falls, it lags real changes and eventually ignores measurements.

Question 3

Why use the Joseph form for the covariance update?

Model answer

It guarantees symmetry and positive semi-definiteness numerically and is valid for any gain, while the short form (II−KH)PP is only exact for the optimal gain and can lose positive definiteness.

References and further reading

Primary papers, official documentation and standards. Each claim above that is specific to a tool or version points here.

What’s next

Mark this lesson

Saved in this browser and synced to your account when you are signed in.

Practice this lesson

M3-L1: Implement a Kalman Filter in Python

Write predict and update for a constant-velocity model.

Next lesson

M3-T5: Extended Kalman Filter

Linearise a nonlinear model with Jacobians, run an EKF, and recognise when linearisation error makes it inconsistent.