public static double[] LsFit(double[] x, double[] y, int order) { //Least squares fit to x, y data int m = Math.Min(x.Length, y.Length); int n = order + 1; int i, j, r; if (m < 1) { throw new Exception("Invalid number of elements for Ls"); } double[] a = new double[m * n]; double[] b = new double[Math.Max(m, n)]; for (i = 0; i < m; ++i) { r = n * i; a[r] = 1.0; b[i] = y[i]; for (j = 1; j < n; ++j) { a[r + j] = x[i] * a[r + j - 1]; } } int info = Lapack.LAPACKE_dgels(Lapack.LAPACK_ROW_MAJOR, 'N', m, n, 1, a, n, b, 1); if (info != 0) { throw new Exception(string.Format("LAPACKE_dgels returned {0}", info)); } double[] c = new double[n]; for (i = 0; i < n; ++i) { c[i] = b[i]; } return(c); }
public static double[] LsSolve(double[] a, int rows, int cols, double[] b) { //Least squares solution of X * A = B, X returned. a is row * col matrix, b is column vector int i; double[] b1 = new double[b.Length]; Array.Copy(b, b1, b.Length); int info = Lapack.LAPACKE_dgels(Lapack.LAPACK_ROW_MAJOR, 'N', rows, cols, 1, a, cols, b1, 1); if (info != 0) { throw new Exception(string.Format("LAPACKE_dgels returned {0}", info)); } double[] c = new double[cols]; for (i = 0; i < cols; ++i) { c[i] = b1[i]; } return(c); }