subplot(2,1,1); plot(t, true_pos, 'g-', 'LineWidth', 2); hold on; plot(t, measurements, 'r.', 'MarkerSize', 8); plot(t, estimated_positions, 'b-', 'LineWidth', 2); legend('True Position', 'Noisy Measurements', 'Kalman Estimate'); xlabel('Time (seconds)'); ylabel('Position (meters)'); title('Kalman Filter: Tracking a Constant Velocity Car'); grid on;
It only needs the previous state to calculate the current state. You don't need a massive database of past readings.
You are in a dark room trying to track the position of a toy car moving at constant velocity. Your only tool? A noisy camera that takes a picture every second. Your only tool
Tracking moving objects or estimating changing states often involves dealing with noisy data. GPS devices drift, sensors fluctuate, and external interference introduces errors. The solves this problem by combining imperfect measurements with mathematical models to find the absolute best estimate of reality.
% Control Input Matrix (External force: Gravity) % We know gravity pulls it down, so we account for it. B = [0.5*dt^2; dt]; u = g; % Input magnitude (acceleration) Predict Step x_hat_minus = x_hat
) to estimate where the system should be at the next time step.
% 3. Update Covariance P = (eye(2) - K * H) * P; end % Plotting Results figure
% 1D Kalman Filter Example: Temperature Tracking clear; clc; close all; % Simulation Parameters true_temp = 72; % The actual constant temperature num_steps = 100; % Number of iterations sensor_noise_sigma = 2; % Standard deviation of measurement noise % Generate noisy measurements rng(42); % Seed for reproducibility measurements = true_temp + sensor_noise_sigma * randn(1, num_steps); % Initialize Kalman Filter Variables estimated_temp = zeros(1, num_steps); P = 10; % Initial estimation error covariance Q = 0.001; % Process noise covariance (highly stable system) R = sensor_noise_sigma^2; % Measurement noise covariance x_hat = 65; % Initial guess % Kalman Filter Loop for k = 1:num_steps % 1. Predict Step x_hat_minus = x_hat; % State prediction (static system) P_minus = P + Q; % Error covariance prediction % 2. Update Step K = P_minus / (P_minus + R); % Calculate Kalman Gain x_hat = x_hat_minus + K * (measurements(k) - x_hat_minus); % Update estimate P = (1 - K) * P_minus; % Update error covariance % Store the result estimated_temp(k) = x_hat; end % Plotting Results figure; plot(1:num_steps, true_temp * ones(1, num_steps), 'g-', 'LineWidth', 2); hold on; plot(1:num_steps, measurements, 'r.', 'MarkerSize', 10); plot(1:num_steps, estimated_temp, 'b-', 'LineWidth', 2); xlabel('Time Step'); ylabel('Temperature (°F)'); title('1D Kalman Filter: Temperature Estimation'); legend('True Value', 'Noisy Measurement', 'Kalman Estimate', 'Location', 'Best'); grid on; Use code with caution. 2D Kalman Filter MATLAB Example (Position and Velocity)