Fitting a line that passes through the origin (0,0) to data

dr_rk picture dr_rk · Sep 19, 2012 · Viewed 13.4k times · Source

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.

Answer

Andrey Rubshtein picture Andrey Rubshtein · Sep 19, 2012

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:

enter image description here

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