用koop的程序构建一个计算ar模型的logmarginallikelihood的函数如下: f nction [logml]=marginal(y); tt = size(y,1); y = y(2:tt); x = y(1:tt-1); x = [ones(tt-1,1) x]; %% %ordinary least sq ares q antities n=size(y,1); bols = (x *x)x *y; s2 = (y-x*bols) *(y-x*bols)(n-1); bolscov = s2*eye(size(x,2))(x *x); bolssd=sqrt(bolscov); v=n-1; %%%%%% prior parameters v0=1; %%%% imaginary data set of v0 observations capv0 = 4*eye(2); capv0inv = inv(capv0) ; %%%%% an imaginary s m x_i^{2} or x x b0 = [0;0.8]; %%% eq ivalent to the ols estimate s02= 0.0001; %%%% an imainary s^2 %posterior hyperparameters for normal-gamma xsq are=x *x; v1=v0+n; capv1inv = capv0inv+ xsq are; capv1=inv(capv1inv); b1 = capv1*(capv0inv*b0 + xsq are*bols); if capv0inv0 v1s12 = v0*s02 + v*s2 + ((bols-b0)^2)(capv0+(1xsq are)); else v1s12 = v0*s02 + v*s2 ; end s12 = v1s12v1; bcov = capv1*v1s12(v1-2); bsd=sqrt(bcov); %posterior mean and variance of error precision hmean = 1s12; hvar=2(v1s12); hsd=sqrt(hvar); %predictive inference xstar=.5; ystarm = xstar*b1; ystarcapv = (1+capv1*xstar^2)*s12; ystarv = ystarcapv*v1(v1-2); ystarsd=sqrt(ystarv); %log of marginal likelihood for the model if prior is informative if v00; intcon=gammaln(.5*v1) + .5*v0*log(v0*s02)- gammaln(.5*v0) 5*n*log(pi); lmarglik=intcon + .5*log(det(capv1)det(capv0)) - .5*v1*log(v1s12); end; logml=lmarglik;