%SAR computes Simultaneous AutoRegression of y on X given weights W 
%    using the multivariate FMINS procedure in MATLAB.(NOTE: This 
%    program assumes that Statistical Toolbox is running.)
%
%INPUTS: (i)   y = n-vector of Yi values
%        (ii)  X = (nxk)-matrix of explanatory variables
%                  (Xi1,..,Xik) [NOT including unit vector]
%        (iii) W = (nxn)-matrix of spatial weights
%        (iv)  varargin = names of variables in X. If the variables 
%              are say "altitude" and "temperature", then the inputs
%              are: (y,X,L,'altitude','temperature')
%
%SCREEN OUTPUT:
%         TABLE1: (REGRESSION RESULTS)
%                 beta coeffs plus z-values for significance tests
%                 (If MATLAB Statistics Toolbox is present, the P-values
%                  are also displayed as 'PROB').
%
%         TABLE2: (GOODNESS OF FIT)
%                 Ps_R2 = Pseudo R-Square (in reduced model)
%                 Sq-Corr = squared correlation coefficient
%                 Lik = value of log likelihood
%
%         TABLE3: (AUTOCORRELATION PARAMETER)
%                 Rho estimate plus z-value for significance tests
%                 (If MATLAB Statistics Toolbox is present, the P-values
%                  are also displayed as 'PROB').
%
%         TABLE4: (TESTS OF SPATIAL AUTOCORRELATION MODEL)
%                 LR  = likelihood ratio for spatial autocorrelation
%                 Com-LR = likelihood ratio for common-factor hyp.


[n,k] = size(X) ;

%Augment X with unit vector

X0 = X ;

XX(:,1) = ones(n,1) ;

XX(:,2:k+1) = X0 ;

%Compute eigen values

val = eig(full(W));

v0 = min(val);

v1 = max(val) ;

low = 1/(-abs(v0)) ;

high = 1/v1 ;


rho = .59198;

B = eye(n) - rho * W ;

u = ones(n,1);

D = eye(n) - (1/n)*u*u' ;


Ps_R2 = (y'*B'*D*B*X*inv(X'*B'*D*B*X)*X'*B'*D*B*y)/(y'*B'*D*B*y) ;


