终于成功仿了一次Kalman滤波器

终于成功仿了一次Kalman滤波器

首先是测试了从网上down的一段代码

% KALMANF - updates a system state vector estimate based upon an
% observation, using a discrete Kalman filter.
%
% Version 1.0, June 30, 2004
%
% This tutorial function was written by Michael C. Kleder
% (Comments are appreciated at: [email protected])
%
% INTRODUCTION
%
% Many people have heard of Kalman filtering, but regard the topic
% as mysterious. While it‘s true that deriving the Kalman filter and
% proving mathematically that it is "optimal" under a variety of
% circumstances can be rather intense, applying the filter to
% a basic linear system is actually very easy. This Matlab file is
% intended to demonstrate that.
%
% An excellent paper on Kalman filtering at the introductory level,
% without detailing the mathematical underpinnings, is:
% "An Introduction to the Kalman Filter"
% Greg Welch and Gary Bishop, University of North Carolina
% http://www.cs.unc.edu/~welch/kalman/kalmanIntro.html
%
% PURPOSE:
%
% The purpose of each iteration of a Kalman filter is to update
% the estimate of the state vector of a system (and the covariance
% of that vector) based upon the information in a new observation.
% The version of the Kalman filter in this function assumes that
% observations occur at fixed discrete time intervals. Also, this
% function assumes a linear system, meaning that the time evolution
% of the state vector can be calculated by means of a state transition
% matrix.
%
% USAGE:
%
% s = kalmanf(s)
%
% "s" is a "system" struct containing various fields used as input
% and output. The state estimate "x" and its covariance "P" are
% updated by the function. The other fields describe the mechanics
% of the system and are left unchanged. A calling routine may change
% these other fields as needed if state dynamics are time-dependent;
% otherwise, they should be left alone after initial values are set.
% The exceptions are the observation vectro "z" and the input control
% (or forcing function) "u." If there is an input function, then
% "u" should be set to some nonzero value by the calling routine.
%
% SYSTEM DYNAMICS:
%
% The system evolves according to the following difference equations,
% where quantities are further defined below:
%
% x = Ax + Bu + w meaning the state vector x evolves during one time
% step by premultiplying by the "state transition
% matrix" A. There is optionally (if nonzero) an input
% vector u which affects the state linearly, and this
% linear effect on the state is represented by
% premultiplying by the "input matrix" B. There is also
% gaussian process noise w.
% z = Hx + v meaning the observation vector z is a linear function
% of the state vector, and this linear relationship is
% represented by premultiplication by "observation
% matrix" H. There is also gaussian measurement
% noise v.
% where w ~ N(0,Q) meaning w is gaussian noise with covariance Q
% v ~ N(0,R) meaning v is gaussian noise with covariance R
%
% VECTOR VARIABLES:
%
% s.x = state vector estimate. In the input struct, this is the
% "a priori" state estimate (prior to the addition of the
% information from the new observation). In the output struct,
% this is the "a posteriori" state estimate (after the new
% measurement information is included).
% s.z = observation vector
% s.u = input control vector, optional (defaults to zero).
%
% MATRIX VARIABLES:
%
% s.A = state transition matrix (defaults to identity).
% s.P = covariance of the state vector estimate. In the input struct,
% this is "a priori," and in the output it is "a posteriori."
% (required unless autoinitializing as described below).
% s.B = input matrix, optional (defaults to zero).
% s.Q = process noise covariance (defaults to zero).
% s.R = measurement noise covariance (required).
% s.H = observation matrix (defaults to identity).
%
% NORMAL OPERATION:
%
% (1) define all state definition fields: A,B,H,Q,R
% (2) define intial state estimate: x,P
% (3) obtain observation and control vectors: z,u
% (4) call the filter to obtain updated state estimate: x,P
% (5) return to step (3) and repeat
%
% INITIALIZATION:
%
% If an initial state estimate is unavailable, it can be obtained
% from the first observation as follows, provided that there are the
% same number of observable variables as state variables. This "auto-
% intitialization" is done automatically if s.x is absent or NaN.
%
%x = inv(H)*z
%P = inv(H)*R*inv(H‘)
%
% This is mathematically equivalent to setting the initial state estimate
% covariance to infinity.
%
% SCALAR EXAMPLE (Automobile Voltimeter):
%
% % Define the system as a constant of 12 volts:
function T
clear s
s.x = 12;
s.A = 1;
% % Define a process noise (stdev) of 2 volts as the car operates:
s.Q = 2^2; % variance, hence stdev^2
% Define the voltimeter to measure the voltage itself:
s.H = 1;
% % Define a measurement error (stdev) of 2 volts:
s.R = 2^2; % variance, hence stdev^2
%Do not define any system input (control) functions:
s.B = 0;
s.u = 0;
% % Do not specify an initial state:
s.x = nan;
s.P = nan;
% % Generate random voltages and watch the filter operate.
tru=[]; % truth voltage
for t=1:20
    tru(end+1) = randn*2+12;
    s(end).z = tru(end) + randn*2; % create a measurement
    s(end+1)=kalmanf(s(end)); % perform a Kalman filter iteration
    % end
    % figure
    % hold on
    % grid on
    % % plot measurement data:
    hz=plot([s(1:end-1).z],‘r‘);hold on
    % % plot a-posteriori state estimates:
    hk=plot([s(2:end).x],‘b-‘);hold on
    ht=plot(tru,‘g-‘);hold on
    legend(‘observations‘,‘Kalman output‘,‘true voltage‘,0)
    title(‘Automobile Voltimeter Example‘)
    % hold off
end    
    
function s = kalmanf(s)

% set defaults for absent fields:
if ~isfield(s,‘x‘); s.x=nan*z; end
if ~isfield(s,‘P‘); s.P=nan; end
if ~isfield(s,‘z‘); error(‘Observation vector missing‘); end
if ~isfield(s,‘u‘); s.u=0; end
if ~isfield(s,‘A‘); s.A=eye(length(x)); end
if ~isfield(s,‘B‘); s.B=0; end
if ~isfield(s,‘Q‘); s.Q=zeros(length(x)); end
if ~isfield(s,‘R‘); error(‘Observation covariance missing‘); end
if ~isfield(s,‘H‘); s.H=eye(length(x)); end

if isnan(s.x)
    % initialize state estimate from first observation
    if diff(size(s.H))
        error(‘Observation matrix must be square and invertible for state autointialization.‘);
    end
    s.x = inv(s.H)*s.z;
    s.P = inv(s.H)*s.R*inv(s.H‘); 
else
    
    % This is the code which implements the discrete Kalman filter:
    
    % Prediction for state vector and covariance:
    s.x = s.A*s.x + s.B*s.u;
    s.P = s.A * s.P * s.A‘ + s.Q;
    
    % Compute Kalman gain factor:
    K = s.P*s.H‘*inv(s.H*s.P*s.H‘+s.R);
    
    % Correction based on observation:
    s.x = s.x + K*(s.z-s.H*s.x);
    s.P = s.P - K*s.H*s.P;
    
    % Note that the desired result, which is an improved estimate
    % of the sytem state vector x and its covariance P, was obtained
    % in only five lines of code, once the system was defined. (That‘s
    % how simple the discrete Kalman filter is to use.) Later,
    % we‘ll discuss how to deal with nonlinear systems.
    
end

后来不过瘾,自己写了一个,没想到稍微改了一改竟然成功了,效果还不错

% 状态
% xk=A•xk-1+B•uk+wk
% zk=H•xk+vk,
% p(w) ~ N(0,Q)
% p(v) ~ N(0,R),

% 预测
% x‘k=A•xk+B•uk
% P‘k=A•P(k-1)*AT + Q
% 修正
% Kk=P‘k•HT•(H•P‘k•HT+R)-1
% xk=x‘k+Kk•(zk-H•x‘k)
% Pk=(I-Kk•H)•P‘k

%要注意的是:必须把系统状态和kalman滤波器内部预测的状态分开
function Test
A=[1 0.1;0 1];
B=0;
Xp=rand(2,1)*0.1; 
X=[0 0]‘;
H=[1 0];
Q=eye(2)*1e-5;
R=eye(1)*0.1; 
P=eye(2);% P‘(k)
angle=[];
angle_m=[];
angle_real=[];
for i=1:500
    angle_real=[angle_real X(1)]; %实际角度
    
    [Xp,P]=Predict(A,Xp,P,Q); 
    
    X=A*X+rand(2,1)*1e-5;
    z_m=H*X+rand(1,1)*0.1-0.05;  
    angle_m=[angle_m z_m(1)];   %测量的角度
        
    [Xp,P]=Correct(P,H,R,X,z_m);
    angle=[angle Xp(1)];     %预测的角度    
end
t=1:500;
plot(t,angle,‘r‘,t,angle_m,‘g‘,t,angle_real,‘b‘)
legend(‘预测值‘,‘测量值‘,‘实际值‘)

figure
plot(t,angle-angle_real,‘r‘,t,angle_m-angle_real,‘g‘)
legend(‘滤波后的误差‘,‘测量的误差‘)
title(‘误差分析‘)
xlabel(‘time‘);
ylabel(‘error‘);

function [Xk,Pk]=Predict(A,Xk,Pk_1,Q)
Xk=A*Xk;
Pk=A*Pk_1*A‘+Q;

function [Xk,Pk]=Correct(Pk,H,R,Xk,zk)
Kk=Pk * H‘ * inv(H * Pk * H‘ + R);
Xk=Xk+ Kk*(zk-H*Xk);
Pk=(eye(size(Pk,1)) - Kk*H)*Pk;

顺便附上几张仿真图
这是状态图

这是误差分析

时间: 2024-08-09 09:59:53

终于成功仿了一次Kalman滤波器的相关文章

Kalman滤波器从原理到实现

转载请注明出处:http://xiahouzuoxin.github.io/notes Kalman滤波器的历史渊源 We are like dwarfs on the shoulders of giants, by whose grace we see farther than they. Our study of the works of the ancients enables us to give fresh life to their finer ideas, and rescue t

运动目标跟踪中kalman滤波器的使用

目标跟踪的kalman滤波器介绍 Kalman滤波器是通过前一状态预测当前状态,并使用当前观测状态进行校正,从而保证输出状态平稳变化,可有效抵抗观测误差.因此在运动目标跟踪中也被广泛使用.在视频处理的运动目标跟踪里,每个目标的状态可表示为(x,y,w,h),x和y表示目标位置,w和h表示目标宽高.一般地认为目标的宽高是不变的,而其运动速度是匀速,那么目标的状态向量就应该扩展为(x,y,w,h,dx,dy),其中dx和dy是目标当前时刻的速度.通过kalman滤波器来估计每个时刻目标状态的大致过程

Kalman滤波器原理和实现

Kalman滤波器原理和实现 kalman filter Kalman滤波器的直观理解[1] 假设我们要测量一个房间下一刻钟的温度.据经验判断,房间内的温度不可能短时大幅度变化,也就是说可以依经验认为下一刻钟的温度等于现在的温度.但是经验是存在误差的,下一刻的真实温度可能比我们预测温度上下偏差几度,这个偏差可以认为服从高斯分布.另外我们也可以使用温度计测量温度,但温度计测量的是局部空间的温度,没办法准确的度量整间房子的平均温度.测量值和真实值得偏差也认为服从高斯分布. 现在希望由经验的预测温度和

【计算机视觉】基于Kalman滤波器的进行物体的跟踪

预估器 我们希望能够最大限度地使用測量结果来预计移动物体的运动. 所以,多个測量的累积能够让我们检測出不受噪声影响的部分观測轨迹. 一个关键的附加要素即此移动物体运动的模型. 有了这个模型,我们不仅能够知道该移动物体在什么位置,同一时候还能够知道我们观察支持模型的什么參数. 该任务分为两个阶段.在第一阶段,即预測阶段.用从过去得到的信息进一步修正模型以取得人或物体的下一个将对出现的位置.在第二阶段,即校正阶段,我们获得一个測量.然后与基于前一次測量的预測值(即模型)进行调整.完毕两个阶段预计任务

终于成功配置 nginx + proxy

今天晚上折腾两个小时,终于成功配置 nginx + proxy 支持以下访问地址,使用的是同一个Flask APP. https://search.readmorejoy.com/ https://markdown.readmorejoy.com/ 初次的学习总是比较折磨人. 单独出 markdown,是因为还要出一个 PC版本 原文地址:https://www.cnblogs.com/pycoding/p/11360979.html

win10安装.net framework3.5,终于成功了

装了win10发现需要运行很多程序时还需要安装.net framework3.5,然后从网上找了好多方法,要么太慢,要么行不通,不过最后终于找到了一个正解方法.. 第一步,挂载或插入安装光盘.在sources\sxs文件夹中会有一个“microsoft-windows-netfx3-ondemand-package.cab”文件.Win+X,以管理员权限启动命令提示符.假设安装盘盘符为X.首先运行:dism.exe /online /add-package /packagepath:X:\sou

我的天,终于成功了

随着电脑重装系统的完成,我好像拥有了一台崭新的电脑一般,幸福o(* ̄▽ ̄*)o!然后就开始风风火火在上面部署自己的“数据科学家”学习环境.过程如下: -R -RStudio -Sublime Text -Java -Scala 后来想弄一个spark的学习环境,在dos受挫后于是又装了: -Scala IDE(eclipse) 然后就开始捣鼓.有了Scala IDE 跟spark还没关系啊,准备弄成spark本地单机模式. 最初下的是spark源码,由于sbt下不来,又重新去下了spark 二进

折腾了好久的macos+apache+php+phpmyadmin 终于成功了!

由于最近需要布置mantis用来进行bug追踪,在此记录其过程. 由于PHP apache环境在Mac OS上是自带的,所以不需要另处下安装包,只需要简单配置一下即可. 首先打开终端输入命令: sudo vim /etc/apache2/httpd.conf 其中有一行是这样的 #LoadModule php5_module libexec/apache2/libphp5.so 将前面的#号去掉. 然后打开系统偏好设置中的共享,将web共享勾上,如下图 重启apache, 命令如下: sudo

终于成功编译并且运行了 android源代码 总结一下 遇到的 问题

android 源代码编译真是 好难呀 ,几个月前我曾经编译过但遇到了各种问题,可能是采用ubuntu12.04的原因,这次下载和编译都很顺利.ubuntu采用14.04 在下载前提前进行了hosts设置,我是吧http://laod.cn/hosts/2015-google-hosts.html 这哥们的 hosts整个粘贴到/etc/hosts 文件中的,采用学校校园网下载,不知道用其他网会不会 出问题,上次下载各种 不能访问. 编译的时候也很顺利,直接编译出来了,我 觉得与系统版本有很大关