Ex3211.m
资源名称:work.rar [点击查看]
上传用户:shigeng
上传日期:2017-01-30
资源大小:122k
文件大小:3k
源码类别:
数值算法/人工智能
开发平台:
Matlab
- function Particle
- % Particle filter
- x = 1; % 初始状态
- Q = 1; % 过程噪声协方差
- R = 1; % 测量噪声协方差
- tf = 100; % 仿真长度
- N = 100; % 粒子滤波器粒子数
- xhat = x;
- P = 2;
- xhatPart = x;
- % 初始化粒子过滤器
- N1=50;
- for i = 1 : N1
- xpart(i) = x + sqrt(P) * randn;
- end
- xArr = [x];
- yArr = [3*x + sqrt(R) * randn];
- xhatArr = [x];
- PArr = [P];
- xhatPartArr = [xhatPart];
- close all;
- % 系统仿真
- x = 3*x + sqrt(Q) * randn;%状态方程
- y = 3*x + sqrt(R) * randn;%观测方程
- % 卡尔曼滤波
- F = 3;
- P = F * P * F' + Q;
- H = xhat ;
- K = P * H' * inv(H * P * H' + R);
- xhat = 3*xhat ;%预测
- xhat = xhat + K * (y - 3*xhat);%更新
- P = (1 - K * H) * P;
- for i = 1 : N1
- xpartminus(i) =3* xpart(i) + sqrt(Q) * randn;
- ypart = 3*xpartminus(i);
- vhat = y - ypart;%观测和预测的差
- q(i) = (1 / sqrt(R) / sqrt(2*pi)) * exp(-vhat^2 / 2 / R);
- end
- %正常化的可能性,每个先验估计
- qsum = sum(q);
- for i = 1 : N1
- q(i) = q(i) / qsum;%归一化权重
- end
- % 重采样
- for i = 1 : N1
- u = rand; % 均匀随机数介于0和1
- qtempsum = 0;
- for j = 1 : N1
- qtempsum = qtempsum + q(j);
- if qtempsum >= u
- xpart(i) = xpartminus(j);
- break;
- end
- end
- xhatPart = mean(xpart);
- xArr = [xArr x];
- yArr = [yArr y];
- xhatArr = [xhatArr xhat];
- PArr = [PArr P];
- xhatPartArr = [xhatPartArr xhatPart];
- x0=50;
- xhat1 = x0;
- xhatPart1 = x0;
- % 初始化粒子过滤器
- for i = 1 : N1
- xpart1(i) = x0 + sqrt(P) * randn;
- end
- xArr1 = [x0];
- yArr1 = [-3*x0 + sqrt(R) * randn];
- xhatArr1 = [x0];
- xhatPartArr1 = [xhatPart1];
- close all;
- % 系统仿真
- x1 = -3* x0 + sqrt(Q) * randn;%状态方程
- y1 = -3*x1+ sqrt(R) * randn;%观测方程
- % 卡尔曼滤波
- F1 = -3 ;
- P1 = F1 * P * F1' + Q;
- H1 = xhat;
- K1 = P1* H1' * inv(H1 * P1 * H1' + R);
- xhat1 = -3 * xhat1 ;%预测
- xhat1 = xhat1 + K1 * (y1 +3*xhat1);%更新
- P1 = (1 - K1 * H1) * P1;
- for i = 1 : N1
- xpartminus1(i) = -3*xpart1(i) + sqrt(Q) * randn;
- ypart1 = -3*xpartminus1(i);
- vhat1 = y1 - ypart1;%观测和预测的差
- vhat00=sqrt(y1.^2-ypart1.^2);
- q1(i) = (1 / sqrt(R) / sqrt(2*pi)) * exp(-vhat1^2 / 2 / R);
- end
- %正常化的可能性,每个先验估计
- qsum = sum(q1);
- for i = 1 : N1
- q1(i) = q1(i) / qsum;%归一化权重
- end
- % 重采样
- for i = 1 : N1
- u = rand; % 均匀随机数介于0和1
- qtempsum = 0;
- for j = 1 : N1
- qtempsum = qtempsum + q(j);
- if qtempsum >= u
- xpart1(i) = xpartminus1(j);
- break;
- end
- end
- xhatPart1 = mean(xpart1);
- xArr1 = [xArr1 x1];
- yArr1 = [yArr1 y1];
- xhatArr1 = [xhatArr1 xhat1];
- PArr = [PArr P];
- xhatPartArr1 = [xhatPartArr1 xhatPart1];
- t1 = 0 : 50;t2=50:100;
- end
- end
- figure;
- plot(t1, xArr, 'b.',t2, xArr1, 'b.', t1,xhatArr,'r', t2,xhatArr1,'r',t1, xhatPartArr, 'k-',t2, xhatPartArr1, 'k-');
- xlabel('time step'); ylabel('state');
- legend('True state','KF', 'Particle filter estimate');