function test = GQ_test(y,X,index,n1,n2,P);
% PURPOSE: Goldfeld-Quandt Test 
% ---------------------------------------------------------------------
%  USAGE: test = GQ_test(y,X,index,n1,n2,P)
%  where: y = dependent variable vector (nobs x 1)
%         X = independent variables matrix (nobs x nvar)
%         index = number of independent variable to order observations
%         n1 = number of observations for the first regression
%         n2 = number of observations for the second regression
%         (r = T-n1-n2 ... omited central observations)
%         P = level of significance (optional) by default P=0.95
% ---------------------------------------------------------------------
%  RETURNS: a structure
%         test.meth     = 'Goldfeld-Quandt'
%         test.Ftest    = empirical value
%         test.Fcrit    = critical value
%         test.result   = 'hypothesis of homoscedasticity (not) rejected'
%         test.homosc   = 1 (not rejected)or 0
% ---------------------------------------------------------------------
 
nIn = nargin;

if nIn < 5
  error('Not enough input arguments.');
elseif nIn > 6
  error('Too many input arguments.');
end

if nIn == 5
  P = 0.95;
end

%Goldfeld-Quandt test
 test.meth = 'Goldfeld-Quandt';
 [nobs,nvar]=size(X);
 pom = sortrows([y X],index+1);
 res_e1 = ols(pom(1:n1,1),pom(1:n1,2:end));
 res_e2 = ols(pom(end-n2+1:end,1),pom(end-n2+1:end,2:end));
    e1 = res_e1.resid;
    e2 = res_e2.resid;
    if (e1'*e1)>(e2'*e2)
        test.Ftest = (e1'*e1/(n1-nvar))/(e2'*e2/(n2-nvar));
    else 
        test.Ftest = (e2'*e2/(n2-nvar))/(e1'*e1/(n1-nvar));
    end
    test.Fcrit = finv(P,n1-nvar,n2-nvar);

    if test.Ftest < test.Fcrit
        test.result = 'hypothesis of homoscedasticity NOT REJECTED';
        test.homosc = 1;
    else
        test.result = 'hypothesis of homoscedasticity REJECTED';
        test.homosc = 0;
    end