-
Notifications
You must be signed in to change notification settings - Fork 0
/
Basic_KF.m
93 lines (83 loc) · 2.42 KB
/
Basic_KF.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function [x_out, time_tot] = Basic_KF(varargin)
% [x_kalman, time_tot] = Basic_KF(y, G, F, dyn_var, obs_var);
%
% This function runs the standard Kalman Filter on the set of measurements
% y taken by the linear operators in G to infer the dynamic signal
% approximately generated by the dynamics F
%
% The inputs are:
%
% y: MxT matrix of measurement vectors at each time step
% G: MxNxT array of measurement matrices at each iteration
% F: MxMxT array of dynamics matrices for each iteration
% dyn_var: Scalar value of the innovations variance (or approximate)
% obs_var: Scalar variance of the measurement noise
%
% The outputs are:
% x_out: NxT matrix with the estimates of the signal x
% time_tot: total runtime
%
%
% Code by Adam Charles,
% Department of Electrical and Computer Engineering,
% Georgia Institute of Technology
%
% Last updated August 14, 2012.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Input Parsing
if nargin > 1
y = varargin{1};
G = varargin{2};
else
error('Bad (too few) number of inputs!')
end
if nargin > 2
F = varargin{3};
else
F = eye(size(G, 2));
end
if nargin > 3
dyn_var = varargin{4};
else
dyn_var = 0.01;
end
if nargin > 4
obs_var = varargin{5};
else
obs_var = 0.01;
end
if nargin > 5
error('Bad (too many) number of inputs!')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initializations
y_dim = size(G, 1);
x_dim = size(F, 1);
num_iters = size(y, 2) - 1;
x_out = zeros(x_dim, num_iters+1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Run Algorithm
tic;
% Initial Point
x_out(:, 1) = pinv(G(:, :, 1))*y(:, 1);
P = zeros(x_dim);
R = obs_var*eye(y_dim);
for ii = 1:num_iters
x_pred = F(:, :, ii+1)*x_out(:, ii); % Predict state
temp = zeros(size(x_pred));
temp(x_pred ~= 0) = dyn_var;
Q = diag(temp);
% Predict variance
P_pred = F(:, :, ii+1)*P*(F(:, :, ii+1).') + Q;
% Calcualte Kalman Gain
K = P_pred*(G(:, :, ii+1).')*pinv(R + G(:, :, ii+1)*P_pred*(G(:, :, ii+1).'));
% Update state estimation
x_out(:, ii+1) = x_pred + K*(y(:, ii+1) - G(:, :, ii+1)*x_pred);
% Update state covariance
P = P_pred - K*G(:, :, ii+1)*P_pred;
end
time_tot = toc;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%