Weighted linear least squares linear fit. How to force through first point on line?

StackOverflow https://stackoverflow.com/questions/14769863

  •  07-03-2022
  •  | 
  •  

Question

I'm using alglib to calculate slope and intercept values using a least squares linear fit equation, as follows:-

int info;
double[] c;
alglib.lsfitreport rep;
var fmatrix = new double[,] { { 1, 0 }, { 1, 0.05 }, { 1, 0.1 }, { 1, 0.2 } };
var y = new double[] { 32046, 32260, 32296, 32678 };
var w = new double[] { 1, 1, 1, 1 };

alglib.lsfitlinearw(y, w, fmatrix, out info, out c, out rep);

var intercept = c[0];
var slope = c[1];

"fmatrix" contains my x-axis values (the second of each pair:- 0, 0.05, 0.1, 0.2); "y" obviously holds my y-axis values; "w" are the weightings - in this case all 1's, so no weightings are applied in this example.

Now, I need to apply a couple of different "forcings". I've managed to find how to "force through origin" by changing the first value of each fmatrix pair from "1" to "0", i.e.:

var fmatrix = new double[,] { { 0, 0 }, { 0, 0.05 }, { 0, 0.1 }, { 0, 0.2 } };

However I also need to force through the first point (x=0, y=32046). Any ideas how to achieve this? Math isn't my strong point and I don't really understand the function's documentation: http://www.alglib.net/translator/man/manual.csharp.html#sub_lsfitlinearw

Was it helpful?

Solution

Apologies, I managed to figure it out. I have to subtract the first point's Y value from all Y values in the array. Then I perform the calculation using "force through origin".

The function will of course return an intercept value of 0, which I should ignore and use the first Y value as the intercept instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top