Possible Duplicate: How to correct 「Function definitions are not permitted at the prompt or in scripts」MATLAB錯誤「在此上下文中不允許使用函數定義。」
不足爲奇的是,如果我嘗試運行MATLAB中的以下中號腳本中,我得到的錯誤
??? Error: File: kalmanmle.m Line: 47 Column: 1 Function definitions are not permitted in this context.
我不能確定這是否可以像我的方式運行。或者,我如何在MATLAB命令行上運行它?
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
F = 0.9;
Q = 0.1;
A = 2;
n = 100;
Hvec = zeros(n,1); %index returns process
indexshock = normal_rnd(0,0.1,n,1);
Hvec(1) = 0;
for i = 2:n,
Hvec(i) = 0.95*Hvec(i-1) + indexshock(i);
end
%H = 0.3;
R = 0.05;
x = ones(n,1);
zhi = zeros(n,1);
y = zeros(n,1);
zhi(1) = 0;
v = normal_rnd(0,Q,n,1);
w = normal_rnd(0,R,n,1);
H = Hvec(1);
y(1) = A'*x(1) + H'*zhi(1) + w(1);
for i = 2:n,
H = Hvec(i);
zhi(i) = F*zhi(i-1) + v(i);
y(i) = A'*x(i) + H'*zhi(i) + w(i);
end
%% ------------------
%test = [zhi y]
function ret = MyLikelihoodFn(p)
global y;
global x;
global Hvec;
F = p(1);
Q = p(2)^2;
A = p(3);
R = p(4)^2;
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'*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'*Ezhi;
tmp3 = -0.5*tmpmat2'*inv(tmpmat)*tmpmat2;
tmpsum = tmp1+tmp2+tmp3;
end
ret = -tmpsum;
endfunction
param = zeros(4,1);
param(1) = 0.2;
param(2) = 0.2;
param(3) = 1;
param(4) = 0.2;
resultparam = fmins('MyLikelihoodFn',param)
actualF = F
F = resultparam(1)
actualQ = Q
Q = resultparam(2)^2
actualA = A
A = resultparam(3)
actualR = R
R = resultparam(4)^2
n = size(y,1);
P = Q;
Ezhi = 0;
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'*Ezhi);
P = F*P*F' - F*P*H*inv(H'*P*H+R)*H'*P*F' + Q;
Ezhivec(i) = Ezhi;
end
test = [zhi Ezhivec Hvec y];
tmp = 1:n;
%plot(tmp,zhi,'-',tmp,Ezhivec,'-',tmp,Hvec,'-',tmp,y,'-');
plot(tmp,zhi,'-',tmp,Ezhivec,'-');
請嘗試使用代碼塊代碼。它看起來像一堆,閱讀起來非常困難。 – ja72 2011-05-12 01:03:10
也相關:[MATLAB中的腳本和函數之間有什麼區別?](http://stackoverflow.com/questions/1695365/whats-the-difference-between-a-script-and-a-function-in -matlab),[在MATLAB中,我可以在同一個文件中有腳本和函數定義嗎?](http://stackoverflow.com/questions/5363397/in-matlab-can-i-have-a-script-和A-函數的定義,在最相同的文件) – gnovice 2011-05-12 02:56:20