Take the 2-minute tour ×

I used to work with MATLAB, and for the question I raised I can use p = polyfit(x,y,1) to estimate the best fit line for the scatter data in a plate. I was wondering which resources I can rely on to implement the line fitting algorithm with C++. I understand there are a lot of algorithms for this subject, and for me I expect the algorithm should be fast and meantime it can obtain the comparable accuracy of polyfit function in MATLAB.

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

I would suggest coding it from scratch. It is a very simple implementation in C++. You can code up both the intercept and gradient for least-squares fit (the same method as polyfit) from your data directly from the formulas here


These are closed form formulas that you can easily evaluate yourself using loops. If you were using higher degree fits then I would suggest a matrix library or more sophisticated algorithms but for simple linear regression as you describe above this is all you need. Matrices and linear algebra routines would be overkill for such a problem (in my opinion).

share|improve this answer
Thanks, and this is a good starting point. –  feelfree Jul 12 '12 at 10:19
add comment

You can also use or go over this implementation there is also documentation here.

share|improve this answer
add comment

to fit a line y=param[0]x+param[1] simply do this: loop over data: {
sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += x[i] * x[i]; }

// means
double mean_x = sum_x / ninliers;
double mean_y = sum_y / ninliers;

float varx = sum_x2 - sum_x * mean_x;
float cov = sum_xy - sum_x * mean_y;

// check for zero varx

param[0] = cov / varx;
param[1] = mean_y - param[0] * mean_x;

More on the topic http://easycalculation.com/statistics/learn-regression.php (formulas are the same, they just multiplied and divided by N, a sample sz.). If you want to fit plane to 3D data use a similar approach - http://www.mymathforum.com/viewtopic.php?f=13&t=8793

Disclaimer: all quadratic fits are linear and optimal in a sense that they reduce the noise in parameters. However, you might interested in the reducing noise in the data instead. You might also want to ignore outliers since they can bia s your solutions greatly. Both problems can be solved with RANSAC. See my post at:

share|improve this answer
add comment

Your Answer


