Reputation: 4565
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.
Upvotes: 10
Views: 15939
Reputation: 21
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.
Upvotes: 2
Reputation: 20915
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
Upvotes: 15
Reputation: 104
if you have the "Curve Fitting Toolbox" you can use
f = fit( x, y, 'a*x' );
Upvotes: 3