diff --git a/src/FSharp/Fit.fs b/src/FSharp/Fit.fs index 3c290cda..28f3f239 100644 --- a/src/FSharp/Fit.fs +++ b/src/FSharp/Fit.fs @@ -59,7 +59,7 @@ module Fit = /// Least-Squares fitting the points (x,y) to an arbitrary linear combination y : x -> p0*f0(x) + p1*f1(x) + ... + pk*fk(x), /// returning its best fitting parameters as [p0, p1, p2, ..., pk] list. - let linear functions (x:float[]) (y:float[]) = + let linear functions (x:_[]) (y:float[]) = functions |> List.map (fun f -> List.init (Array.length x) (fun i -> f x.[i])) |> DenseMatrix.ofColumnsList (Array.length x) (List.length functions) diff --git a/src/Numerics/Fit.cs b/src/Numerics/Fit.cs index d339b72d..13dd2f5d 100644 --- a/src/Numerics/Fit.cs +++ b/src/Numerics/Fit.cs @@ -31,7 +31,6 @@ using System; using System.Linq; using MathNet.Numerics.LinearAlgebra.Double; -using MathNet.Numerics.LinearAlgebra.Generic; using MathNet.Numerics.LinearAlgebra.Generic.Factorization; using MathNet.Numerics.Properties; @@ -160,5 +159,27 @@ namespace MathNet.Numerics var parameters = LinearMultiDim(x, y, functions); return z => functions.Zip(parameters, (f, p) => p * f(z)).Sum(); } + + /// + /// Least-Squares fitting the points (T,y) = (T,y) to an arbitrary linear combination y : X -> p0*f0(T) + p1*f1(T) + ... + pk*fk(T), + /// returning its best fitting parameters as [p0, p1, p2, ..., pk] array. + /// + public static double[] LinearGeneric(T[] x, double[] y, params Func[] functions) + { + return DenseMatrix + .OfRows(x.Length, functions.Length, x.Select(xi => functions.Select(f => f(xi)))) + .QR(QRMethod.Thin).Solve(new DenseVector(y)) + .ToArray(); + } + + /// + /// Least-Squares fitting the points (T,y) = (T,y) to an arbitrary linear combination y : X -> p0*f0(T) + p1*f1(T) + ... + pk*fk(T), + /// returning a function y' for the best fitting combination. + /// + public static Func LinearGenericFunc(T[] x, double[] y, params Func[] functions) + { + var parameters = LinearGeneric(x, y, functions); + return z => functions.Zip(parameters, (f, p) => p * f(z)).Sum(); + } } }