Excel slope function (continued)

Aug 24, 2012 at 2:30 AM

Dear Peoples, i have been trying to find a simple calculation in .net whereby we may send in two arrays (one for y values, another for x values), and it returns the slope.  This exists in Excel and is very easy to use (yes, even i can do this).  However, when it comes to doing this in .Net, i have not found anything simple, resembling this calculation.

Can someone point me in the right direction?  please note, i am a layman, and so if someone could show us how to return the slope value for these two arrays, that would be just great!

 

Thank you in advance for your kindness.

Jorge Guerreiro

Coordinator
Aug 24, 2012 at 10:18 AM
Edited Aug 24, 2012 at 10:22 AM

Hi

What you're looking for is called linear regression. This is the most requested feature and we'll work on it, but only after the next v2.2 release.

In the meantime, the following snippet should do the trick:

using MathNet.Numerics.LinearAlgebra.Double

double[] xdata = new double[] { 10, 20, 30 };
double[] ydata = new double[] { 15, 20, 25 };

var X = DenseMatrix.CreateFromColumns(new[] {new DenseVector(xdata.Length, 1), new DenseVector(xdata)});
var Y = DenseMatrix.CreateFromColumns(new[] {new DenseVector(ydata)});
var coeff = X.QR().Solve(Y);

var slope = coeff[1, 0];
var y0 = coeff[0, 0];

Thanks,
Christoph 

Marked as answer by cdrnet on 10/3/2013 at 3:35 PM
Aug 26, 2012 at 6:12 PM

Hi Christoph, thank you for prompt reply.  will give it a test and will report back on outcome.

Thanks again and stay well.

Aug 27, 2012 at 1:16 AM

Looks like the CreateFromColumns doesnt exist in the DenseMatrix class.  I am using the most recent downloaded MathNet.Numerics from this site.  Any thoughts?  Perhaps I am missing a using ?

Thank you

Jorge

Aug 27, 2012 at 1:23 AM

Looks like the CreateFromColumns doesnt exist in the DenseMatrix class.  I am using the most recent downloaded MathNet.Numerics from this site.  Any thoughts?  Perhaps I am missing a using ?

Thank you

Jorge

Coordinator
Aug 27, 2012 at 6:05 PM

Please try again with v2.2.

Thanks,
Christoph 

Jul 8, 2013 at 5:29 PM

HI Guys, just wanted to check in to see if this has been implemented.

Thank you kindly

You guys Rock!

Jorge

Coordinator
Jul 8, 2013 at 9:21 PM
Edited Jul 8, 2013 at 9:24 PM
It has indeed, but just a couple weeks ago and will be part of the next release, v2.6 (current release is v2.5). You can get pre-release binaries here if needed (see artifacts column).

In v2.6 you can now simply call Fit.Line, which will return a length-2 array containing offset (y for x=0) and slope of the best fitting line (least squares):
var x = new double[] {...}; var y = new double[] {...}
double[] p = Fit.Line(x, y);
var slope = p[1];
Marked as answer by cdrnet on 10/3/2013 at 3:35 PM