If sensor noise is low, the filter trusts the measurement more. 1D Kalman Filter: Tracking a Constant Temperature
fprintf('RMSE of Raw Measurements: %.2f meters\n', rmse_before); fprintf('RMSE of Kalman Filter: %.2f meters\n', rmse_after);
Kalman filters rely heavily on state-space representations ( Tuning Q and R: Q (Process Noise): If your model is poor, increase Q. If sensor noise is low, the filter trusts
The code provided in Part 3 is your starting line. Copy it into MATLAB (2020b or newer works perfectly). Run it. Then change measurement_noise_std to 10 and see how the filter reacts. Then change Q to [1,0;0,1] and see how it becomes aggressive.
For a beginner, you don't need to derive them. You just need to know: Copy it into MATLAB (2020b or newer works perfectly)
% 2D Kalman Filter Example: Object Tracking (Position & Velocity) clear; clc; close all; dt = 0.1; % Time step (seconds) num_steps = 50; % System Matrices A = [1 dt; 0 1]; % State transition matrix C = [1 0]; % Measurement matrix (we only measure position) % Noise Covariances Q = [0.001 0; 0 0.001]; % Process noise R = 4; % Measurement noise variance (meters squared) % Real trajectories generation true_x = zeros(2, num_steps); % [position; velocity] true_x(:,1) = [0; 5]; % Starts at 0m, moving at 5 m/s for k = 2:num_steps true_x(:,k) = A * true_x(:,k-1) + sqrt(Q) * randn(2,1); end % Generate noisy position measurements noisy_pos = true_x(1,:) + sqrt(R) * randn(1, num_steps); % Filter Initialization kf_est = zeros(2, num_steps); kf_est(:,1) = [0; 0]; % Initial guess P = eye(2) * 10; % Initial uncertainty % Kalman Filter Loop for k = 2:num_steps % Predict x_pred = A * kf_est(:,k-1); P_pred = A * P * A' + Q; % Update K = (P_pred * C') / (C * P_pred * C' + R); kf_est(:,k) = x_pred + K * (noisy_pos(k) - C * x_pred); P = (eye(2) - K * C) * P_pred; end % Plotting Position Tracking figure; plot(1:num_steps, true_x(1,:), 'g-', 'LineWidth', 2); hold on; plot(1:num_steps, noisy_pos, 'r.', 'MarkerSize', 10); plot(1:num_steps, kf_est(1,:), 'b--', 'LineWidth', 2); xlabel('Time Steps'); ylabel('Position (m)'); title('2D Kalman Filter: Position Tracking'); legend('True Position', 'Measured Position', 'Kalman Estimate'); grid on; Use code with caution. 5. How to Download and Run These Examples To use these scripts on your computer: Open (or the free alternative, GNU Octave ). Create a new script file by clicking New Script .
3. MATLAB Example 1: Estimating a Constant Value (1D Kalman Filter) Then change Q to [1,0;0,1] and see how it becomes aggressive
Consider a discrete linear time‑invariant system: x_k = A x_k-1 + B u_k-1 + w_k-1 z_k = H x_k + v_k where x_k is the state, u_k control input, z_k measurement, w_k process noise ~ N(0,Q), v_k measurement noise ~ N(0,R).
: It minimizes the uncertainty (variance) of the estimates, making it the "best" guess mathematically. Two-Step Loop :