A customer recently asked how to reproduce the results of the MATLAB polyfit
function in NMath. This is easily done using NMath in C#.
MATLAB | NMath | |
---|---|---|
Standard package | CenterSpace.NMath.Analysis |
|
polyfit( x, y, degree ) |
PolynomialLeastSquares( degree, x, y ) |
|
Notes: polynomial coefficients are returned in the reverse order. | ||
|
For example, here’s some MATLAB code for fitting a polynomial of degree 6 to some data, and then evaluating the fitted polynomial at a point (x = 0.25
).
x = [0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3
1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5]
y = [0 0.112462916018285 0.222702589210478 0.328626759459127 0.428392355046668 0.520499877813047 0.603856090847926 0.677801193837419 0.742100964707661 0.796908212422832 0.842700792949715 0.880205069574082 0.910313978229635 0.934007944940652 0.952285119762649 0.966105146475311 0.976348383344644 0.983790458590775 0.989090501635731 0.992790429235257 0.995322265018953 0.997020533343667 0.998137153702018 0.998856823402643 0.999311486103355 0.999593047982555]
p = polyfit(x,y,6)
p = 0.0084 -0.0983 0.4217 -0.7435 0.1471 1.1064 0.0004
f = polyval(p, 0.25);
f = 0.2762
Here’s the equivalent C# NMath code:
#using CenterSpace.NMath.Analysis
public void FitData()
{
DoubleVector x = new DoubleVector("[0 0.1 0.2 0.3 0.4 0.5
0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1
2.2 2.3 2.4 2.5]");
DoubleVector y = new DoubleVector("[0 0.112462916018285 0.222702589210478 0.328626759459127 0.428392355046668 0.520499877813047 0.603856090847926 0.677801193837419 0.742100964707661 0.796908212422832 0.842700792949715 0.880205069574082 0.910313978229635 0.934007944940652 0.952285119762649 0.966105146475311 0.976348383344644 0.983790458590775 0.989090501635731 0.992790429235257 0.995322265018953 0.997020533343667 0.998137153702018 0.998856823402643 0.999311486103355 0.999593047982555]");
PolynomialLeastSquares pls = new PolynomialLeastSquares( 6, x, y );
Console.WriteLine( pls.Coefficients );
Console.WriteLine();
Console.WriteLine( pls.FittedPolynomial.Evaluate( 0.25 ) );
}
This creates the output.
[ 0.000441173961987631 1.10644604462547 0.147104056633056 -0.743462849129717 0.421736169818002 -0.0982995753367523 0.00841937177923124 ] 0.276183548385269
Note that the order of the coefficient vector in NMath is reversed relative that returned from MATLAB’s polyfit()
function. In NMath, the constant is at index 0
and the leading coefficient is at index Coefficients.Length - 1
. If you wish, you can use the Reverse()
method on the coefficient vector to reverse the ordering.
-Ken
Notes
Visualization provided in partnership with Nevron