% Fixed Effects Estimator
% Originally written in Gauss by Olvar Bergland
% Modified and Translated into MATLAB by Wonho Song, October 2002
% E-mail: whsong@kiep.go.kr, whsong73@hotmail.com

function [bw,sef,sw,ew,FIX,EFIX,R2w]=panelf(y,x,n);

[nt,k]=size(x);

t  =  nt/n;          
k1 = k+1;
nk = n*k1;
n1 = n-1;

in = eye(n);                 
it = eye(t);                 
jt = ones(t,1);              
jn = ones(n,1);              

%    fixed-effects model 

dt = it - jt*jt'/t;

%yi = kron(in,dt)*y;
%xi = kron(in,dt)*x;

yi=[];xi=[];

for i=1:n
j1=t*(i-1)+1;j2=j1+t-1;
ind=[j1:j2];
yi=[yi;dt*y(ind,:)];
xi=[xi;dt*x(ind,:)];
end;

xxi = inv(xi'*xi);      
bw  = xxi*xi'*yi;                
ew  = yi - xi*bw;               
sw  = ew'*ew/(nt-n-k);           
sef = sqrt(sw*(diag(xxi)));     

% bw = coefficient
% sef= standard error
% sw = variance of residual

% Calculation of R2 
ey=y-mean(y);
R2w=1-(ew'*ew)/(ey'*ey);
R2w=[R2w;1-(1-R2w)*(nt-1)/(nt-k-n)];


temp=y-x*bw;
temp=temp-mean(temp);

FIX=mean(reshape(temp,t,n))';   % Fixed Effects
FIX=FIX-mean(FIX);

EFIX=exp(FIX-max(FIX));

