%参数设置:初始位置为0,初始速度为0/可以自己设置其他的值
%二维CV运动
%线性卡尔曼滤波
%如果需要EKF,UKF,CKF等,可以咨询823618313@qq.com
%KF
clc; close all; clear all;
N=200;
Runs=200;
T=1;
q_x=0.1;q_y=q_x;%过程噪声方差
Qk=diag([q_x^2,q_y^2]);
r=0.5;%量测噪声方差
Rk=diag([r^2,r^2]);
w_mu=[0,0]'; % mean of process noise
v_mu=[0,0]'; % mean of measurement noise
% state matrix
Fk= [1 T 0 0
0 T 0 0
0 0 1 T
0 0 0 T]; %
Gk= [ T^2/2 0
T 0
0 T^2/2
0 T ]; %
Hk=[1,0,0,0
0,0,1,0];
sV=zeros(4,N,Runs);
mV=zeros(2,N,Runs);
eV=zeros(4,N,Runs);
PV=zeros(4,4,N,Runs);
for i=1:Runs
x=[0, 0, 0, 0]';%初始值
P0=diag([1e0, 1e-2, 1e0, 1e-2]);
% xk=[x', zeros(1,6)]'; Pk=blkdiag(P0, Qk,Qk, Qk);
xk=x; Pk=P0;
x0=mvnrnd(x,P0);
x=x0';
%%
% process white noise
% for k=1:N; w(k)=w_mu+sqrt(Qk)*randn(2,1); end
% for k=1:N; v=v_mu+r*randn(2,1); end
for k=1:T:N
%状态方程
w=mvnrnd(w_mu',Qk)';
w1=w_mu+sqrt(Qk)*randn(2,1);
x=Fk*x+Gk*w;
sV(:,k,i)=x;
%测量方程
v=mvnrnd(v_mu',Rk)';
z=Hk*x+v;
%预测
xkk=Fk*xk;
Pkk=Fk*Pk*Fk'+ Gk*Qk*Gk';
%更新
K=Pkk*Hk'*inv(Hk*Pkk*Hk'+Rk);
xk=xkk+K*(z-Hk*xkk);
Pk=Pkk-Pkk*Hk'*inv((Hk*Pkk*Hk'+Rk))*Hk*Pkk';
eV(:,k,i)=xk;
PV(:,:,k,i)=Pk;
end
end
for i=1:Runs
for k=1:N
error=sV(:,k,i)-eV(:,k,i);
error2=error.^2;
error_p(k,i)=error2(1)+error2(3);
error_v(k,i)=error2(2)+error2(4);
end
end
rms_p=sqrt(sum(error_p,2)/Runs);
rms_v=sqrt(sum(error_v,2)/Runs);
figure
plot(sV(1,:,1),sV(3,:,1),'-k',eV(1,:,1),eV(3,:,1),'--r')
xlabel('m');ylabel('m');
legend('State','KF')
ii=1:N;
figure;%position
plot(ii,sV(1,ii,1),'-k',ii,eV(1,ii,1),'--r')
legend('State','KF')
xlabel('t/s');ylabel('x');
title('position_x')
figure;%position
plot(ii,sV(2,ii,1),'-k',ii,eV(2,ii,1),'--r')
legend('State','KF')
xlabel('t/s');ylabel('x');
title('velocity_x')
figure;%position
plot(ii,rms_p(ii),'-r','LineWidth',0.7);
legend('KF ')
xlabel('t/s');ylabel('RMSE');
title('position-RMS analyze')
figure;%position
plot(ii,rms_v(ii),'-b','LineWidth',0.7);
legend('KF')
xlabel('t/s');ylabel('RMSE');
title('velocity-RMS analyze')
评论0