Matlab卡尔曼滤波器代码 - 为什么不工作?

时间:2016-11-06 12:07:50

标签: matlab kalman-filter

我在这里创建了这段代码:

    while ((index < (sizeof(myStr)/sizeof(myStr[0]))) && (myStr[index] != '*'))

加载hon.txt和 加载dji.txt

正确加载为101 x 1双打。

当我跑步时,我得到以下内容:

myStr[3]

让我感到惊讶,因为在工作区我可以看到

clear all;

%  State space reprsentation to be forcasted by kalman filter
%   zhi(t+1) = F*zhi(t) + v(t+1)   --> unbobserved varaibles
%   v~N(0,Q)
%   y(t) = A'*x(t) + H'*zhi(t) + w(t)
%   w~N(0,R)

global y;
global x;
global Hvec;
%%----    Enter  Input parameters
load hon.txt %filename for stock prices
load dji.txt %filename for index prices
n=100; %no. of points to consider
offset=1; %use 1 for daily return or 30 for monthly return
%-------------------------------


datapts=1:offset:(n+1)*offset;
dji=dji(datapts);
hon=hon(datapts);

%Hvec=(dji(1:n)-dji(2:n+1))./dji(2:n+1); %index returns process
%y=(hon(1:n)-hon(2:n+1))./hon(2:n+1); %index returns process

Hvec=log(dji(1:n)./dji(2:n+1)); %index returns process
y=log(hon(1:n)./hon(2:n+1)); %stock returns process

Hvec=flipud(Hvec);
y=flipud(y);


x=ones(n,1);




param=zeros(5,1);
F=0.5;
F=-log(1/F-1);
param(1)=F;
param(2)=0.2;
param(3)=1;
param(4)=0.2;
param(5)=0.5;

resultparam=fminsearch(MyLikelihoodFn,param)


F=resultparam(1)
F=1/(1+exp(-F))
Q=resultparam(2)^2
A=resultparam(3)
R=resultparam(4)^2
betai=resultparam(5)

n=size(y,1);
P=Q;
Ezhi=0.01;
Ezhivec=zeros(n,1);
Ezhivec(1)=Ezhi;

for i=2:n
  yt=y(i);
  xt=x(i);
  H=Hvec(i);
  Ezhi = F*Ezhi + F*P*H*inv(H'*P*H+R)*(yt-A'*xt-H'*betai-H'*Ezhi);
  P = F*P*F' - F*P*H*inv(H'*P*H+R)*H'*P*F' + Q;
  Ezhivec(i)=Ezhi;
end
Ezhivec=Ezhivec+betai;
test=[Ezhivec Hvec y];
tmp=1:n;
subplot(3,1,1);
plot(tmp,y,'-');
subplot(3,1,2);
plot(tmp,Hvec,'-');
subplot(3,1,3);
plot(tmp,Ezhivec,'-');

%plot(tmp,Ezhivec,'-',tmp,Hvec,'-',tmp,y,'-');
%plot(tmp,zhi,'-',tmp,Ezhivec,'-');


%% ------------------
%test=[zhi y]

function ret=MyLikelihoodFn(p)
  global y;
  global x;
  global Hvec;
  F=p(1);
  F=1/(1+exp(-F));
  Q=p(2)^2;
  A=p(3);
  R=p(4)^2;
  betai=p(5);
  n=size(y,1);
  P=Q;
  Ezhi=0;
  Ezhivec=zeros(n,1);
  Ezhivec(1)=Ezhi;
  tmpsum=0;
  tmp1=-(n/2)*log(2*pi);
  for i=2:n
    yt=y(i);
    xt=x(i);
    H=Hvec(i);
    Ezhi = F*Ezhi + F*P*H*inv(H'*P*H+R)*(yt-A'*xt-H'*betai-H'*Ezhi);
    P = F*P*F' - F*P*H*inv(H'*P*H+R)*H'*P*F' + Q;
    Ezhivec(i)=Ezhi;
    tmpmat = H'*P*H + R;
    tmp2 = -0.5*log(det(tmpmat));
    tmpmat2 = yt - A'*xt - H'*betai - H'*Ezhi;
    tmp3=-0.5*tmpmat2'*inv(tmpmat)*tmpmat2;
    tmpsum=tmp1+tmp2+tmp3;
  end
  ret=-tmpsum;   
end

...

我很困惑......

1 个答案:

答案 0 :(得分:0)

当你说

时,你需要明确告诉MATLAB
resultparam = fminsearch(MyLikelihoodFn, param);

您希望传递给fminsearch的是函数MyLikelihoodFn本身,而不是调用它的结果。 (MATLAB将裸函数名称视为该函数的调用。)

所以在它前面放一个@

resultparam = fminsearch(@MyLikelihoodFn, param);