Example 1: Non-negative Least Squares

Consider the following problem:

\begin{bmatrix}1 & -3 & 2\\ -3 & 10 & -5\\ 2 & -5 & 6\end{bmatrix} \begin{bmatrix}x_1\\ x_2\\ x_3\end{bmatrix} = \begin{bmatrix}27\\ -78\\ 64\end{bmatrix}

Subject to the constraint x \ge 0. The NonNegativeLeastSquares class is used to compute a solution, which is compared to the exact solution of {1, -4, 7}.


import com.imsl.math.*;

public class NonNegativeLeastSquaresEx1 {

    public static void main(String args[]) throws Exception {
        double a[][] = {
            {1, -3, 2},
            {-3, 10, -5},
            {2, -5, 6}
        };
        double b[] = {27, -78, 64};

        NonNegativeLeastSquares nnls = new NonNegativeLeastSquares(a, b);
        nnls.solve();
        double[] x = nnls.getSolution();

        new PrintMatrix("Solution").print(x);

        // compare solution with exact answer
        double[][] compare = new double[2][];
        compare[0] = Matrix.multiply(a, x);
        compare[1] = Matrix.multiply(a, new double[]{1, -4, 7});

        PrintMatrixFormat pmf = new PrintMatrixFormat();
        pmf.setColumnLabels(new String[]{"x >= 0", "exact"});
        PrintMatrix pm = new PrintMatrix("Comparison of 'b'");
        pm.print(pmf, Matrix.transpose(compare));
    }
}

Output

 Solution
     0     
0  18.449  
1   0      
2   4.507  

 Comparison of 'b'
   x >= 0   exact  
0   27.464    27   
1  -77.884   -78   
2   63.942    64   

Link to Java source.