Skip to content

Least squares line fitting

Martijn Koopman edited this page Jun 13, 2019 · 7 revisions

Fit a line through a set of points while minimizing the sum of the squares of the residuals.

Graph

The line is defined by equation: y = ax + b

We wish to calculate a (slope) and b (y-intercept).

Points

X Y
2 20
6 18
20 10
30 6
40 2

Code

#include <spatium/Matrix.h>
#include <spatium/Vector.h>

// Create matrix with variables of line equation
spatium::Matrix A = {
  {  2, 1 },
  {  6, 1 },
  { 20, 1 },
  { 30, 1 },
  { 40, 1 },
};

// Create vector with Y values
spatium::Vector b = { 20, 18, 10, 6, 2 };

// Least squares
Vector c = (A.transposed() * A).inverse() * A.transposed() * b;

// Extract coefficients of line equation
double slope = c(0);
double yIntercept = c(1);

Result:

slope = -0.48
yIntercept = 20.62

Example from: https://ltcconline.net/greenl/courses/203/MatrixOnVectors/leastSquares.htm