I have a set of points (x,y)
and I need to find the line of best-fit that passes through the origin using MATLAB.
Asked
Active
Viewed 1.5k times
10

Andrey Rubshtein
- 20,795
- 11
- 69
- 104

dr_rk
- 4,395
- 13
- 48
- 74
-
1How do you define your criterion for a "best fit"? Least square error? – Eitan T Sep 19 '12 at 14:13
-
1Yes that's right - thanks for pointing that out as its important. – dr_rk Sep 20 '12 at 05:27
3 Answers
15
In short: Your function must be in the form of y=ax+0
, which makes polyfit
useless. But you can use the least squares method:
a = x(:)\y(:);
Explanation:
You have n
equations and one variable a
that is needed to be found:
a*x1 = y1;
a*x2 = y2;
...
a*xn = yn;
The operator \
finds the least squares solution.
Alternatively, you can find the solution manually:
a = (x'*x) \ (x'*y);
or in Pseudo code:
(x1*y1 + x2*y2 + ... xn*yn)
a = ----------------------------
(x1*x1 + x2*x2 + ... xn*xn)
This is useful if you are not using Matlab - for example in C code.
Example and code snippet:
function FindLSSolution()
a = 2.5;
x = rand(100,1)*10;
y = a*x + randn(100,1);
figure;scatter(x,y);
A = x(:)\y(:);
hold on;plot(x, A*x,'g');
end

Andrey Rubshtein
- 20,795
- 11
- 69
- 104
-
1@dr_rk, Yes, but it is not recommended because it is slower and less stable numerically – Andrey Rubshtein Sep 19 '12 at 13:29
2
The best fit line, in general, passes through the centroid of the data (average the x's and average the y's). So find the centroid and plot the line from the origin through the centroid.

David Chandler
- 21
- 2