Resilient Pose Estimation Using Terrain-Aided Inertial Sensor Fusion in GPS-Denied Environments
R2026bThis example shows how to fuse inertial sensor measurements with a radar altimeter and a digital elevation model (DEM) to maintain accurate pose estimation when GPS is unavailable. A radar altimeter measures the aircraft's height above ground level (AGL), and a DEM stores the ground elevation at each location in the region. The example estimates the aircraft pose with an extended Kalman filter (EKF), created with insEKF. To turn the altimeter reading into a position correction, a custom insEKF sensor plugin predicts what the altimeter should read: it takes the current position estimate from the filter, reads the ground elevation at that location from the DEM, and subtracts it from the estimated altitude to get the predicted AGL. The mismatch between this prediction and the actual measurement by the radar altimeter drives position corrections proportional to the local terrain slope.
The filter (EKF) linearizes the terrain around the current position estimate, approximating the terrain surface by its local slope. This slope is the measurement Jacobian. It sets how strongly a height mismatch corrects position. When the measured AGL does not match the predicted AGL, the filter corrects position in proportion to the local terrain slope. Over varied terrain, a nonzero AGL residual implies a position error, because the DEM elevation depends on position.

Background
Inertial navigation systems (INS) integrate accelerometer and gyroscope measurements to estimate position, velocity, and attitude. Without external corrections, sensor biases cause position error to grow as . GPS normally provides these corrections, but is unavailable in contested, jammed, or underground environments.
Terrain-aided navigation (TAN) works because the height above ground changes as the aircraft moves over hills and valleys. Fly over higher ground and the altimeter reads a smaller height. The altimeter measures AGL. The filter predicts what this AGL should be from its current position estimate. It subtracts the DEM elevation at the estimated North-East position (N, E) from the estimated altitude. When the measured AGL differs from this prediction, the filter infers a position error and applies corrections scaled by terrain slope.
The key insight is that over varied terrain, elevation is a unique function of North-East position. The measurement Jacobian is H = [-dDEM/dN, -dDEM/dE, -1]. The partial derivatives of terrain elevation with respect to North and East position appear directly as correction gains. When terrain is steep (large dDEM/dN or dDEM/dE), the AGL residual produces proportionally large North or East corrections. Over flat terrain these derivatives are zero, and the residual constrains only altitude.

Setup
rng(42) imuRate = 100; % Hz gpsRate = 1; % Hz tanRate = 10; % Hz — radar altimeter correlation rate dt = 1 / imuRate;
Load Digital Elevation Model
Terrain data for this example covers mountainous terrain near South Boulder Peak, Colorado, from a DTED (Digital Terrain Elevation Data) file [1]. DTED stores elevation above mean sea level (MSL) on a regular latitude-longitude grid and is a standard format used by military and civilian navigation systems. Both the DEM and the filter operate in the same local NED (North-East-Down) frame, computed by helperLoadDEM, so their elevations share a common reference. This example pre-computes the elevation, latitude, and longitude grids from the DTED file using readgeoraster (Mapping Toolbox) and saves them as a MAT file:
[dem, demRef] = readgeoraster("n39_w106_3arc_v2.dt1"); [lat, lon] = geographicGrid(demRef); save("demData.mat", "dem", "lat", "lon", "-v7.3");
For details on reading and displaying elevation data, see the example. This DTED Level 1 file has ~92 m post spacing — suitable for demonstrating the terrain-aided navigation concept, but coarse for operational use. The griddedInterpolant created by helperLoadDEM interpolates between posts to provide continuous elevation queries. For real applications, use a higher-resolution DEM to reduce interpolation error — for example, GeoTIFF elevation rasters (SRTM 30 m or lidar-derived 1–5 m) loaded via readgeoraster. Higher resolution directly reduces the terrain measurement noise required in the filter and improves position accuracy. The radar altimeter sensor model requires a griddedInterpolant in the local NED frame. You can either provide elevation, latitude, and longitude arrays to helperLoadDEM (which handles the geodetic-to-NED conversion), or construct a NED griddedInterpolant directly if your data is already in a local frame.
data = load("demData.mat", "dem", "lat", "lon"); latLim = [39.50 39.70]; lonLim = [-105.55 -105.45]; refLoc = [mean(latLim), mean(lonLim), 0]; [demInterpolant, nVec, eVec] = helperLoadDEM(data.dem, data.lat, data.lon, latLim, lonLim, refLoc);
Simulate Flight and Sensor Measurements
The scenario simulates a fixed-wing reconnaissance aircraft entering a known GPS-denied zone. helperGenerateTANTrajectory generates the trajectory and sensor data. It internally uses:
waypointTrajectory— smooth interpolation between waypoints with specified velocitiesimuSensor— accelerometer and gyroscope measurements with bias and noise. ConfigureNoiseDensity,ConstantBias, andBiasInstabilityfrom your sensor datasheet to create a digital twin of your hardware.gpsSensor— GPS position and velocity measurements. SetHorizontalPositionAccuracyandVelocityAccuracyto match your receiver specifications.altimeterSensor— radar altimeter AGL measurements with a simple noise model. For higher-fidelity altimeter simulation usingphased.FMCWWaveformandradarScenario, see the example, which demonstrates waveform generation and range processing that accounts for beam geometry and surface scattering. For real sensor data, provide measured AGL values directly to the fusion loop.
The aircraft maintains constant velocity (50 m/s) with a gentle 45° right turn. This flight profile is deliberate: fixed-wing aircraft require minimum airspeed, and aggressive maneuvers degrade pose estimation because insMotionPose assumes constant acceleration between updates. For trajectories with rapid dynamics, derive a custom motion model from positioning.INSMotionModel to capture higher-order motion. At 0.36 m/s² maximum acceleration, this trajectory stays well within insMotionPose capabilities.
Three mission phases:
GPS available (0–60 s): Establishes an accurate navigation state. This includes position, velocity, and, critically, the inertial measurement unit (IMU) bias estimates that persist through GPS denial.
GPS denied (60–180 s): INS + terrain aiding only. The filter relies on gyroscope integration to maintain heading and terrain aiding to bound position drift.
GPS reacquired (180–240 s): Error converges back as GPS corrections resume
At 50 m/s cruise speed, the aircraft traverses 5 m between each 10 Hz terrain measurement. Because terrain elevation varies spatially, each measurement at a new position samples a different DEM elevation, giving the filter a fresh constraint to refine its horizontal position estimate.
[traj, imuData, gpsData, radarAltData, gpsOutageIdx] = ... helperGenerateTANTrajectory(refLoc, demInterpolant, dt, imuRate, gpsRate); N = numel(traj.time); fprintf("Trajectory: %.0f s, %d samples\n", traj.time(end), N);
Trajectory: 240 s, 24000 samples
fprintf("GPS outage: %.0f-%.0f s (%.0f s duration)\n", ... traj.gpsOutageStart, traj.gpsOutageEnd, ... traj.gpsOutageEnd - traj.gpsOutageStart);
GPS outage: 60-180 s (120 s duration)
helperVisualizeTerrainNav.plotScenario(demInterpolant, nVec, eVec, traj, gpsOutageIdx)

The 3D surface plot shows the mountainous DEM region with elevation ranging from valleys to ridges. The plot overlays the flight path and highlights the GPS-denied segment separately. Notice the path crosses multiple ridges and valleys during GPS denial. This exposes the filter to varied terrain gradients that enable both North and East corrections.
Radar Altimeter Sensor Model
The helperInsTerrainAltimeter class implements the terrain measurement model as an insEKF plugin by subclassing positioning.INSSensorModel. This superclass defines the interface that every custom insEKF sensor must implement. The interface consists of a measurement method and a measurementJacobian method. During the correction step, the insEKF filter calls the measurement method to predict the altimeter reading and the measurementJacobian method to compute the Kalman gain.
type helperInsTerrainAltimeter.mclassdef helperInsTerrainAltimeter < positioning.INSSensorModel
%HELPERINSTERRAINALTIMETER insEKF sensor plugin for terrain-aided navigation
%
% Predicts the height above ground level (AGL) at the current estimated
% position by looking up the DEM. The innovation (measured AGL minus
% predicted AGL) drives position corrections through terrain slope.
%
% Measurement model:
% z = -pos_D - DEM(pos_N, pos_E)
%
% Jacobian (nonzero entries at Position state indices via stateinfo):
% H = [0,...,0, -dDEM/dN, -dDEM/dE, -1, 0,...,0]
%
% Terrain slope interpolants are precomputed from the DEM grid for
% efficient and accurate Jacobian evaluation.
% Copyright 2026 The MathWorks, Inc.
properties
TerrainMapInterpolant % griddedInterpolant for DEM (meters MSL)
SlopeNorthInterpolant % griddedInterpolant for dDEM/dN
SlopeEastInterpolant % griddedInterpolant for dDEM/dE
end
methods
function sensor = helperInsTerrainAltimeter(terrainMap)
arguments
terrainMap
end
sensor.TerrainMapInterpolant = terrainMap;
% Precompute terrain slope interpolants from DEM grid
nVec = terrainMap.GridVectors{1};
eVec = terrainMap.GridVectors{2};
elev = terrainMap.Values;
dN = mean(diff(nVec));
dE = mean(diff(eVec));
[dFdE, dFdN] = gradient(elev, dE, dN);
sensor.SlopeNorthInterpolant = griddedInterpolant({nVec, eVec}, dFdN, 'linear');
sensor.SlopeEastInterpolant = griddedInterpolant({nVec, eVec}, dFdE, 'linear');
end
function z = measurement(sensor, filt)
pos = stateparts(filt, 'Position');
z = -pos(3) - sensor.TerrainMapInterpolant(pos(1), pos(2));
end
function dzdx = measurementJacobian(sensor, filt)
N = numel(filt.State);
dzdx = zeros(1, N);
pos = stateparts(filt, 'Position');
posIdx = stateinfo(filt, 'Position');
dzdx(1, posIdx(1)) = -sensor.SlopeNorthInterpolant(pos(1), pos(2));
dzdx(1, posIdx(2)) = -sensor.SlopeEastInterpolant(pos(1), pos(2));
dzdx(1, posIdx(3)) = -1;
end
end
end
The class has three key parts:
Constructor — Takes a griddedInterpolant DEM and precomputes terrain slope interpolants (dDEM/dN and dDEM/dE) from the grid using gradient. Precomputing avoids repeated finite-difference calculations during the filter loop.
measurement method — Predicts AGL at the current filter position estimate: z = -pos_D - DEM(pos_N, pos_E). This is the expected radar altimeter reading if the position estimate is correct. The difference between the measured AGL and this prediction, called the innovation, drives the corrections.
measurementJacobian method — Returns the 1-by-N Jacobian (where N is the number of filter states) H = [0,...,0, -dDEM/dN, -dDEM/dE, -1, 0,...,0] where the method places the nonzero entries at the Position state indices (determined by stateinfo(filt, 'Position')). The -1 in the Down column provides direct altitude observability. The terrain slopes (dDEM/dN, dDEM/dE) couple the altitude residual into North and East position corrections. This coupling is the mechanism that constrains horizontal drift using a vertical measurement. Over flat terrain these slopes are zero and only altitude is correctable.
Customizing the Sensor Model
To use a higher-fidelity altimeter model or alternative terrain correlation technique, subclass positioning.INSSensorModel and override:
measurement(sensor, filt)— Return predicted measurement(s) given the current filter state. For example, an FMCW radar model can account for beam footprint averaging over the illuminated ground area rather than a single point lookup.measurementJacobian(sensor, filt)— Return the M×N Jacobian of measurements with respect to the full state vector. If an analytical Jacobian is not available, omit this method andinsEKFcomputes a numerical Jacobian automatically (at the cost of M+1 calls tomeasurementper correction step).
For batch correlation approaches (comparing a measured altitude profile against candidate DEM strips), the EKF point-measurement framework might not apply directly. In that case, consider using the plugin to fuse a position correction from an external correlator rather than raw altitude.
altSensor = helperInsTerrainAltimeter(demInterpolant);
Configure insEKF
The filter fuses three sensor types: IMU (accelerometer + gyroscope) at 100 Hz, GPS at 1 Hz (when available), and radar altimeter at 10 Hz. The motion model (insMotionPose) tracks 16 states: quaternion orientation, body angular velocity, NED position, velocity, and acceleration. Its state transition assumes constant acceleration. Acceleration changes during maneuvers appear as process noise, the allowance the filter makes for unmodeled dynamics. This is adequate for gentle maneuvers (< 0.5 m/s²). For aggressive fixed-wing dynamics, derive a custom motion model from positioning.INSMotionModel that accounts for centripetal acceleration during turns.
accSensor = insAccelerometer; gyroSensor = insGyroscope; gpsSensor = insGPS; gpsSensor.ReferenceLocation = refLoc; filt = insEKF(accSensor, gyroSensor, gpsSensor, altSensor, insMotionPose); stateinfo(filt)
ans = struct with fields:
Orientation: [1 2 3 4]
AngularVelocity: [5 6 7]
Position: [8 9 10]
Velocity: [11 12 13]
Acceleration: [14 15 16]
Accelerometer_Bias: [17 18 19]
Gyroscope_Bias: [20 21 22]
The helperConfigureTANFilter function initializes filter state, sets process noise and initial state covariance, and defines measurement noise covariances. Key tuning choices documented in that helper:
Process noise: Acceleration (0.5 m²/s⁴) accommodates maneuver dynamics. If you set it too high, the filter distrusts its acceleration estimate. If you set it too low, the residuals corrupt orientation. Orientation and gyro bias noise are very low to preserve heading stability during GPS denial.
Initial covariance: Position 1 m, velocity 0.1 m/s, matching GPS accuracy from the 60 s calibration phase. Bias covariances are small because they persist through the outage and directly determine drift rate.
Terrain measurement noise (R = 9 m²): Conservative because DEM interpolation error between 92 m grid posts dominates, and the linearized terrain correction is only valid in a small neighborhood around the current estimate.
Edit helperConfigureTANFilter to adjust these parameters for your sensor quality and flight dynamics. The header comments document the rationale for each value.
noiseParams = helperConfigureTANFilter(filt, ... Orientation=compact(traj.orientation(1)), ... Position=traj.posNED(1,:), ... Velocity=traj.velNED(1,:)); Raccel = noiseParams.Raccel; Rgyro = noiseParams.Rgyro; Rgps = noiseParams.Rgps; Rterrain = noiseParams.Rterrain;
Incremental Estimation with Live Tracking
Run the EKF predict-fuse loop incrementally with an animated geoplot showing the aircraft position in real time. The loop fuses GPS at 1 Hz when available and fuses the radar altimeter at 10 Hz throughout the flight.
gpsSampleInterval = round(imuRate / gpsRate); tanSampleInterval = round(imuRate / tanRate); poseUpdateInterval = imuRate; estPos = zeros(N, 3); estVel = zeros(N, 3); [~, trailLine, uavMarker] = helperVisualizeTerrainNav.setupLiveTracking(traj, gpsOutageIdx); for i = 1:N predict(filt, dt); fuse(filt, accSensor, imuData.accel(i,:), Raccel); fuse(filt, gyroSensor, imuData.gyro(i,:), Rgyro); if gpsData.available(i) && mod(i, gpsSampleInterval) == 0 fuse(filt, gpsSensor, gpsData.lla(i,:), Rgps); end if mod(i, tanSampleInterval) == 0 fuse(filt, altSensor, radarAltData.agl(i), Rterrain); end estPos(i,:) = stateparts(filt, 'Position'); estVel(i,:) = stateparts(filt, 'Velocity'); if mod(i, poseUpdateInterval) == 0 helperVisualizeTerrainNav.updateLiveTracking(uavMarker, trailLine, estPos, estVel, i, poseUpdateInterval, refLoc); end end

The blue trail shows the EKF position estimate on a satellite basemap. During the GPS-available phase (first 60 s), the estimate closely tracks the truth trajectory (gray). When GPS is lost at 60 s, terrain corrections keep the trail on course through the 120 s outage. The GPS-denied segment of the truth trajectory is highlighted in red for reference.
Baseline Comparison
To quantify the value of terrain aiding, run an identical filter without the radar altimeter sensor model. During GPS denial, the baseline relies solely on IMU dead-reckoning — all three position components drift unbounded. North and East errors grow as gyroscope bias causes heading drift that accumulates into lateral displacement. Down (altitude) error grows by a different mechanism: accelerometer bias integrates twice (bias → velocity error → position error), accumulating directly into altitude without involving heading. Without any vertical reference, there is nothing to arrest this vertical drift.
accSensorBL = insAccelerometer; gyroSensorBL = insGyroscope; gpsSensorBL = insGPS; gpsSensorBL.ReferenceLocation = refLoc; filtBaseline = insEKF(accSensorBL, gyroSensorBL, gpsSensorBL, insMotionPose); helperConfigureTANFilter(filtBaseline, ... Orientation=compact(traj.orientation(1)), ... Position=traj.posNED(1,:), ... Velocity=traj.velNED(1,:)); estPosBaseline = zeros(N, 3); for i = 1:N predict(filtBaseline, dt); fuse(filtBaseline, accSensorBL, imuData.accel(i,:), Raccel); fuse(filtBaseline, gyroSensorBL, imuData.gyro(i,:), Rgyro); if gpsData.available(i) && mod(i, gpsSampleInterval) == 0 fuse(filtBaseline, gpsSensorBL, gpsData.lla(i,:), Rgps); end estPosBaseline(i,:) = stateparts(filtBaseline, 'Position'); end
Smoothed Estimate
The estimateStates function implements an RTS (Rauch-Tung-Striebel) smoother — a backward pass over the entire trajectory that uses future measurements to refine past estimates. Because it requires the complete forward filter history, smoothing is an offline post-mission step (not real-time). It provides the best achievable accuracy for a given sensor configuration, making it useful for post-mission analysis such as survey or mapping. The computational cost is roughly double that of the forward pass. Call estimateStates with two outputs to obtain the smoothed solution.
accSensorSm = insAccelerometer; gyroSensorSm = insGyroscope; gpsSensorSm = insGPS; gpsSensorSm.ReferenceLocation = refLoc; altSensorSm = helperInsTerrainAltimeter(demInterpolant); filtSmooth = insEKF(accSensorSm, gyroSensorSm, gpsSensorSm, altSensorSm, insMotionPose); helperConfigureTANFilter(filtSmooth, ... Orientation=compact(traj.orientation(1)), ... Position=traj.posNED(1,:), ... Velocity=traj.velNED(1,:)); sensorData = timetable(seconds(traj.time), ... imuData.accel, imuData.gyro, ... VariableNames=["Accelerometer", "Gyroscope"]); gpsIdx = false(N, 1); gpsIdx(1:gpsSampleInterval:N) = true; gpsIdx(gpsOutageIdx) = false; tanIdx = false(N, 1); tanIdx(1:tanSampleInterval:N) = true; sensorData.GPS = nan(N, 3); sensorData.GPS(gpsIdx, :) = gpsData.lla(gpsIdx, :); sensorData.helperInsTerrainAltimeter = nan(N, 1); sensorData.helperInsTerrainAltimeter(tanIdx) = radarAltData.agl(tanIdx); measureNoise = struct( ... "AccelerometerNoise", Raccel, ... "GyroscopeNoise", Rgyro, ... "GPSNoise", Rgps, ... "helperInsTerrainAltimeterNoise", Rterrain); [~, smoothedEst] = estimateStates(filtSmooth, sensorData, measureNoise); smoothPos = smoothedEst.Position;
Performance Evaluation
Position error is shown as separate North, East, and Down components on a log scale, along with a 3D trajectory comparison.
helperVisualizeTerrainNav.plotPerformance(traj, estPos, estPosBaseline, smoothPos)


Error plot (log scale): The baseline (red) shows the dominant error is in the Down component — accelerometer bias double-integrates into altitude drift that grows unbounded without a vertical reference. North and East errors remain moderate because the 60 s GPS calibration phase estimates gyroscope bias well enough to maintain heading. The filtered estimate (blue) maintains bounded error in all axes. Because the altimeter measures altitude directly, the filter tightly bounds the Down error through the -1 term in the Jacobian (the Down column), and terrain slope corrections provide additional North and East constraint over varied terrain. The smoothed estimate (green) achieves the lowest error by propagating future measurements backward. After GPS reacquisition at 180 s, all estimates converge rapidly.
3D trajectory: The baseline (red) diverges primarily vertically from truth during the outage. Altitude drift dominates because no vertical reference exists without terrain aiding. The filtered (blue) and smoothed (green) traces remain close to truth (black). The altitude constraint from the terrain-aided filter is the most immediate benefit; North and East (N/E) corrections via slope coupling provide additional improvement over varied terrain.
Summary
This example demonstrated resilient pose estimation using terrain-aided inertial fusion in a GPS-denied environment. The custom insEKF plugin fuses radar altimeter readings with a DEM. It bounds altitude directly, and where terrain has slope, it uses that vertical measurement to bound North and East drift as well.
Key findings:
Terrain matching reduces position error by an order of magnitude during GPS denial
The filtered (real-time) solution corrects drift using terrain, keeping error low throughout the outage
The RTS smoother further improves accuracy by propagating future information backward
Effectiveness scales directly with terrain gradient. Steep terrain gives the strongest corrections
Practical Considerations
Terrain Observability
A state is observable when measurements respond to changes in that state. Over flat terrain (deserts, open water, plains), the terrain slope approaches zero and the altimeter measurement constrains only altitude. North and East are unobservable because the measurement does not change with horizontal position. Mission planning should assess terrain slope along the intended flight path to determine where TAN will be effective.
Yaw Drift: Dominant Error Source
Heading drift from gyroscope bias is the single biggest factor limiting TAN accuracy. Once the heading estimate diverges, the ground track predicted by the filter no longer matches the true track. Terrain corrections computed at the wrong position push the estimate further off rather than correcting it. In this example, low orientation process noise preserves gyroscope heading during GPS denial, but the portion of gyroscope bias not fully estimated during the GPS phase still causes monotonic heading drift over 120 seconds.
Maneuver Sensitivity
The insMotionPose constant-acceleration model works well for gentle dynamics (< 0.5 m/s²). During aggressive turns, the Acceleration state lags reality because it assumes da/dt = 0. The resulting accelerometer measurement residual couples into the orientation estimate through the Kalman gain. In testing, a 19-second coordinated turn at 25 m/s² centripetal corrupted heading by 250° with accelerometer fusion, compared to only 4° with gyroscope-only orientation tracking. The trajectory in this example deliberately maintains gentle maneuvers to avoid this coupling.
Altitude and Beam Coverage
Radar altimeters are most effective at low-to-moderate altitudes (50–500 m AGL) where the beam footprint is small relative to terrain features. At higher altitudes, the beam illuminates a larger ground area. The return then represents an averaged elevation over the footprint rather than a point measurement, reducing effective terrain resolution for position correction.
Terrain-Following vs. Constant Altitude
Actively following terrain (constant AGL) reduces the altitude measurement innovation because AGL stays approximately constant regardless of position. Constant MSL altitude over varied terrain produces large AGL variations that provide stronger position corrections through the terrain slope Jacobian.
Extending with Additional Sensors
The positioning.INSSensorModel pattern used here extends to other position-dependent measurements that address the limitations above:
Barometric altimeter — Provides a stable, terrain-independent altitude reference, directly constraining the Down state and freeing the terrain altimeter innovation to focus on N/E corrections via slope coupling
Magnetometer — Constrains heading (yaw) directly through Earth's magnetic field. Because yaw drift is the dominant TAN error source, even a noisy magnetometer keeps the heading estimate accurate enough that terrain corrections are applied at approximately the correct position
Magnetic anomaly maps — Local magnetic field variations create position-dependent signatures for N/E correction that work even over flat terrain where radar altimeters cannot help. This complements terrain matching: topography works over mountains, magnetics work over geologically distinctive regions
Together, these sensors address the three main TAN limitations: yaw drift (magnetometer), altitude-vs-position ambiguity in the terrain residual (barometer), and flat-terrain blindness (magnetic anomaly maps).
References
[1] The elevation data used in this example is from the US Geological Survey.