10

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.

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
dr_rk
  • 4,395
  • 13
  • 48
  • 74

3 Answers3

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:

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
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
3

if you have the "Curve Fitting Toolbox" you can use

f = fit( x, y, 'a*x' );
Daniel
  • 104
  • 4
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.