-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKalmanFilter.cpp
More file actions
119 lines (94 loc) · 2.04 KB
/
KalmanFilter.cpp
File metadata and controls
119 lines (94 loc) · 2.04 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* Write a function 'filter()' that implements a multi-
* dimensional Kalman Filter for the example given
*/
#include <iostream>
#include <vector>
#include "Dense"
using std::cout;
using std::endl;
using std::vector;
using Eigen::VectorXd;
using Eigen::MatrixXd;
// Kalman Filter variables
VectorXd x; // object state
MatrixXd P; // object covariance matrix
VectorXd u; // external motion
MatrixXd F; // state transition matrix
MatrixXd H; // measurement matrix
MatrixXd R; // measurement covariance matrix
MatrixXd I; // Identity matrix
MatrixXd Q; // process covariance matrix
vector<VectorXd> measurements;
void filter(VectorXd &x, MatrixXd &P);
int main() {
/**
* Code used as example to work with Eigen matrices
*/
// design the KF with 1D motion
x = VectorXd(2);
x << 0, 0;
P = MatrixXd(2, 2);
P << 1000, 0, 0, 1000;
u = VectorXd(2);
u << 0, 0;
F = MatrixXd(2, 2);
F << 1, 1, 0, 1;
H = MatrixXd(1, 2);
H << 1, 0;
R = MatrixXd(1, 1);
R << 1;
I = MatrixXd::Identity(2, 2);
Q = MatrixXd(2, 2);
Q << 0, 0, 0, 0;
// create a list of measurements
VectorXd single_meas(1);
single_meas << 1;
measurements.push_back(single_meas);
single_meas << 2;
measurements.push_back(single_meas);
single_meas << 3;
measurements.push_back(single_meas);
// call Kalman filter algorithm
filter(x, P);
return 0;
}
void filter(VectorXd &x, MatrixXd &P) {
for (unsigned int n = 0; n < measurements.size(); ++n) {
VectorXd z = measurements[n];
// TODO: YOUR CODE HERE
// KF Measurement update step
VectorXd y = z - H*x;
MatrixXd S = H*P*H.transpose() + R;
MatrixXd K = P*H.transpose()*S.inverse();
// new state
x = x + K*y;
P = (I - K*H)*P;
// KF Prediction step
x = F*x + u;
P = F*P*F.transpose() + Q;
cout << "x=" << endl << x << endl;
cout << "P=" << endl << P << endl;
}
}
/*
Output:
x=
0.999001
0
P=
1001 1000
1000 1000
x=
2.998
0.999002
P=
4.99002 2.99302
2.99302 1.99501
x=
3.99967
1
P=
2.33189 0.999168
0.999168 0.499501
*/