[9] | 1 | function testKF(skipgen) |
---|
[22] | 2 | if nargin<1, skipgen=0; end |
---|
[7] | 3 | |
---|
[9] | 4 | if ~skipgen |
---|
| 5 | A=[1 -0.5; 1 0]; |
---|
[33] | 6 | B=[1;0.1]; |
---|
[37] | 7 | C=[1 0];%; 0 1]; |
---|
| 8 | D=0.1;%[0.1; 0]; |
---|
[62] | 9 | R=0.01;%[1 0; 0 0.1]; |
---|
[33] | 10 | Q=[0.2 0 ; 0 0.2]; |
---|
[7] | 11 | |
---|
[9] | 12 | sQ = chol(Q)'; |
---|
| 13 | sR = chol(R)'; |
---|
[7] | 14 | |
---|
[37] | 15 | N =3000; |
---|
[9] | 16 | mu0 = [0;0]; |
---|
| 17 | P0 = 200*eye(2); |
---|
[7] | 18 | |
---|
[37] | 19 | u = zeros(1,N); |
---|
[9] | 20 | x = zeros(2,N); |
---|
[37] | 21 | y = zeros(1,N); |
---|
[7] | 22 | |
---|
[9] | 23 | x(:,1) = [10;10]; |
---|
[32] | 24 | Et = sQ*randn(2,N); |
---|
[37] | 25 | Wt = sR*randn(1,N); |
---|
[9] | 26 | for i=2:N; |
---|
[32] | 27 | x(:,i) = A*x(:,i-1) + B*u(i) + Et(:,i); |
---|
| 28 | y(:,i) = C*x(:,i) + D*u(i) + Wt(:,1); |
---|
[9] | 29 | end |
---|
[7] | 30 | |
---|
[9] | 31 | d=[y;u]; |
---|
| 32 | itsave('testKF.it',d,A,B,C,D,Q,R,P0,mu0) |
---|
| 33 | save testKF |
---|
| 34 | else |
---|
| 35 | load testKF |
---|
| 36 | end |
---|
[7] | 37 | % init |
---|
[8] | 38 | mu = mu0; |
---|
| 39 | P = P0; |
---|
| 40 | EP = [0;0]; |
---|
[7] | 41 | |
---|
[32] | 42 | Oxt = mu0; |
---|
| 43 | OPt = P0; |
---|
| 44 | ll =0; |
---|
[37] | 45 | oxt = mu0; |
---|
| 46 | oPt = chol(P0)'; |
---|
| 47 | oll=0; |
---|
[32] | 48 | |
---|
[37] | 49 | tic; |
---|
[7] | 50 | for t=2:N |
---|
[91] | 51 | mu = A*mu + B*u(t); |
---|
| 52 | P = A*P*A' + Q; |
---|
[7] | 53 | |
---|
[91] | 54 | %Data update |
---|
| 55 | Ry = C*P*C' + R; |
---|
| 56 | iRy = inv(Ry); |
---|
| 57 | K = P*C'*iRy; |
---|
| 58 | P = P- K*C*P; % P = P -KCP; |
---|
| 59 | mu = mu + K*(y(:,t)-C*mu-D*u(t)); |
---|
| 60 | Mu(1:2,t)=mu; |
---|
| 61 | |
---|
[37] | 62 | [Oxt,OPt,ll(t)] = Kalman(Oxt,y(:,t),A,C,Q,R,OPt); |
---|
| 63 | % [oxt,oPt,oll(t)] = KalmanSq(oxt,y(:,t),A,C,sQ,sR,oPt); |
---|
| 64 | MuK(1:2,t) = Oxt; |
---|
| 65 | % MuS(1:2,t) = oxt; |
---|
[7] | 66 | end |
---|
[37] | 67 | exec_matlab = toc |
---|
| 68 | %keyboard |
---|
[7] | 69 | |
---|
[22] | 70 | !cd ../;./tests/testKF |
---|
[7] | 71 | itload('testKF_res.it'); |
---|
| 72 | |
---|
| 73 | hold off |
---|
| 74 | plot(x'); |
---|
| 75 | hold on |
---|
[91] | 76 | plot([xth]','--'); % shift the predldmatictions |
---|
[8] | 77 | plot(xth2','+'); |
---|
[22] | 78 | plot(xthE','o'); |
---|
[37] | 79 | plot([zeros(size(xth,1),1) MuK]','d'); % shift the predictions |
---|
| 80 | |
---|
| 81 | exec_times |
---|
| 82 | exec_matlab./exec_times |
---|
[62] | 83 | keyboard |
---|
| 84 | end |
---|