function Particle_GS
clear;
echo off;
N=80;
T=1;
t=1:1:N;
x0=0.1;
R=1;
Q=10;
initVar=5;
numSamples=500;
M=100;
tic
v=sqrt(R)*randn(N,1);
w=sqrt(Q)*randn(N,1);
% figure(1);
% clf;
% subplot(221)
% plot(v);
% ylabel('Measurement Noise','fontsize',15);
% xlabel('Time');
% subplot(222);
% plot(w);
% ylabel('Process Noise','fontsize',15);
% xlabel('Time');
x=zeros(N,1);
y=zeros(N,1);
x(1,1)=x0;
y(1,1)=(x(1,1)^2)./20+v(1,1);
for k=2:N
x(k,1)=0.5*x(k-1,1)+2.5*x(k-1,1)/(1+x(k-1,1)^(2))+8*cos(1.2*k)+w(k-1,1);
y(k,1)=(x(k,1).^(2))./20+v(k,1);
end;
subplot(223);
plot(x);
ylabel('State x','fontsize',15);
xlabel('Time','fontsize',15);
subplot(224);
plot(y);
ylabel('Observation y','fontsize',15);
xlabel('Time','fontsize',15);
x_pf=zeros(numSamples,N);
xu_pf=zeros(numSamples,N);
y_pf=zeros(numSamples,N);
q_pf=zeros(numSamples,N);
x_pf(:,1)=x0+sqrt(initVar)*randn(numSamples,1);
y_pf(:,1)=x_pf(:,1).^2/20;
for k=2:N
w1=sqrt(Q).*randn(numSamples,1);
xu_pf(:,k)=0.5.*x_pf(:,k-1)+2.5.*x_pf(:,k-1)./(1+x_pf(:,k-1).^2)...
+8*cos(1.2*k)+w1;
y_pf(:,k)=(xu_pf(:,k).^2)./20;
for i=1:numSamples
q_pf(i,k)=exp(-.5*R^(-1)*(y(k,1)-y_pf(i,k))^2);
end;
q_pf(i,k)=q_pf(i,k)/sum(q_pf(:,k));
u=rand(numSamples,1);
u=sort(u);
l=cumsum(q_pf(:,k));
i=1;
for j=1:numSamples
while(i<=numSamples)&(u(i)<=l(j))
x_pf(i,k)=xu_pf(j,k);
i=i+1;
end
end
end
xmean_pf=mean(x_pf);
bins=20;
xmap_pf=zeros(N,1);
for k=1:N
[p,pos]=hist(x_pf(:,k,1),bins);
map=find(p==max(p));
xmap_pf(k,1)=pos(map(1));
end;
xrmse_pf=sqrt(sum((x'-xmean_pf).^2)/N);
for k=1:N
xstd_pf(1,k)=std(x_pf(:,k)-x(k,1));
end
time=toc
figure(2)
clf;
plot(t,x,'k-',t,xmean_pf,'c-*',t,xmap_pf,'r-.');
legend('真实轨迹','后验均值估计','MAP估计');
ylabel('状态估计','fontsize',15);
xlabel('时间','fontsize',15);
% figure(3);
% subplot(121);
% plot(xmean_pf,x,'+')
% ylabel('True state','fontsize',15);
% xlabel('Posterior mean estimate','fontsize',15);
% hold on;
% c=-25:1:25;
% plot(c,c,'r');
% axis([-25 25 -25 25]);
% hold off;
% subplot(122);
% plot(xmap_pf,x,'+')
% ylabel('True state','fontsize',15);
% xlabel('MAP estimate','fontsize',15);
% hold on;
% c=-25:1:25;
% plot(c,c,'r');
% axis([-25 25 -25 25]);
% hold off;
% domain=zeros(numSamples,1);
% range=zeros(numSamples,1);
% parameter=1;
% bins=10;
% support=[-20,1,20];
% figure(4);
% hold on;
% ylabel('Time','fontsize',15);
% xlabel('Sample space','fontsize',15);
% zlabel('Posterior density','fontsize',15);
% v=[0,1];
% caxis(v);
% for k=1:2:N
% [range,domain]=hist(x_pf(:,k,parameter),support);
% waterfall(domain,k,range);
% end;
figure(5);
plot(t,xstd_pf,'-');
xlabel('时间 (t/s)');
ylabel('状态估计误差标准差');
axis([0,N,0,10]);
评论1