### Question:
GeneralizedLeastSquaresRegression extends LeastSquaresRegression { @Override public LeastSquaresRegressionResult regress(double[][] x, double[][] weights, double[] y, boolean useIntercept) { if (weights == null) { throw new IllegalArgumentException("Cannot perform GLS regression without an array of weights"); } checkData(x, weights, y); double[][] dep = addInterceptVariable(x, useIntercept); double[] indep = new double[y.length]; double[][] wArray = new double[y.length][y.length]; for (int i = 0; i < y.length; i++) { indep[i] = y[i]; for (int j = 0; j < y.length; j++) { wArray[i][j] = weights[i][j]; } } DoubleMatrix matrix = DoubleMatrix.copyOf(dep); DoubleArray vector = DoubleArray.copyOf(indep); DoubleMatrix w = DoubleMatrix.copyOf(wArray); DoubleMatrix transpose = ALGEBRA.getTranspose(matrix); DoubleMatrix betasVector = (DoubleMatrix) ALGEBRA.multiply( ALGEBRA.multiply( ALGEBRA.multiply( ALGEBRA.getInverse(ALGEBRA.multiply(transpose, ALGEBRA.multiply(w, matrix))), transpose), w), vector); double[] yModel = super.writeArrayAsVector(((DoubleMatrix) ALGEBRA.multiply(matrix, betasVector)).toArray()); double[] betas = super.writeArrayAsVector(betasVector.toArray()); return getResultWithStatistics(x, y, betas, yModel, useIntercept); }  @Override LeastSquaresRegressionResult regress(double[][] x, double[][] weights, double[] y, boolean useIntercept);  }### Answer:
@Test public void test() { final double a0 = 2.3; final double a1 = 4.7; final double a2 = -0.99; final double a3 = -5.1; final double a4 = 0.27; final int n = 30; final double[][] x = new double[n][4]; final double[] yIntercept = new double[n]; final double[] yNoIntercept = new double[n]; final double[][] w = new double[n][n]; double y, x1, x2, x3, x4; for (int i = 0; i < n; i++) { x1 = i; x2 = x1 * x1; x3 = Math.sqrt(x1); x4 = x1 * x2; x[i] = new double[] {x1, x2, x3, x4}; y = x1 * a1 + x2 * a2 + x3 * a3 + x4 * a4; yNoIntercept[i] = y; yIntercept[i] = y + a0; for (int j = 0; j < n; j++) { w[i][j] = 0.; } w[i][i] = 1.; } final GeneralizedLeastSquaresRegression regression = new GeneralizedLeastSquaresRegression(); final OrdinaryLeastSquaresRegression olsRegression = new OrdinaryLeastSquaresRegression(); LeastSquaresRegressionResult gls = regression.regress(x, w, yIntercept, true); LeastSquaresRegressionResult ols = olsRegression.regress(x, yIntercept, true); assertRegressions(n, 5, gls, ols); gls = regression.regress(x, w, yNoIntercept, false); ols = olsRegression.regress(x, yNoIntercept, false); assertRegressions(n, 4, gls, ols); gls = regression.regress(x, w, yIntercept, true); ols = olsRegression.regress(x, yIntercept, true); assertRegressions(n, 5, gls, ols); gls = regression.regress(x, w, yNoIntercept, false); ols = olsRegression.regress(x, yNoIntercept, false); assertRegressions(n, 4, gls, ols); }