Subject to the constraint . The NonNegativeLeastSquares class is used to compute a solution, which is compared to the exact solution of {1, -4, 7}.
using System; using Imsl.Math; public class NonNegativeLeastSquaresEx1 { public static void Main(String[] args) { 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, 3]; double[] tmp1 = Matrix.Multiply(a, x); double[] tmp2 = Matrix.Multiply(a, new double[]{1, - 4, 7}); for (int i = 0; i < compare.GetLength(1); i++) { compare[0, i] = tmp1[i]; compare[1, i] = tmp2[i]; } PrintMatrixFormat pmf = new PrintMatrixFormat(); pmf.SetColumnLabels(new String[]{"x >= 0", "exact"}); PrintMatrix pm = new PrintMatrix("Comparison of 'b'"); pm.Print(pmf, Matrix.Transpose(compare)); } }
Solution 0 0 18.4492753623188 1 0 2 4.5072463768116 Comparison of 'b' x >= 0 exact 0 27.463768115942 27 1 -77.8840579710145 -78 2 63.9420289855073 64Link to C# source.