Fitting a line that passes through the origin (0,0) to data
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
if you have the "Curve Fitting Toolbox" you can use
f = fit( x, y, 'a*x' );