Post by Steven LordPost by Seth GilchristI want to use polyfit in a script file and force the y-intercept of
the fit line to zero.
...
Post by Steven Lordy/x = a_n*x^(n-1)+a_(n-1)*x^(n-2)...+a_2*x+a_1
Steve's idea is a good one if you are willing to minimize the sum of squared
residuals on this scale:
sum((y/x - estimated y/x)^2)
(using a notation that is somewhere in between math and MATLAB). If you
want to minimize the sum of squared residuals on the original scale:
sum((y-estimated y)^2),
then you can do something like this to fit a polynomial up to 3rd degree:
b = [x.^3, x.^2, x] \ y;
This gives you the coefficient estimates. If you need the 2nd and 3rd
outputs from polyfit you'd have to do a bit more. You shouldn't use polyfit
the usual way and then set the last element of p to 0 manually -- that would
give the wrong answer. You should, though, add an extra 0 element for the
constant term to b, if you intend to use polyval to evaluate the polynomial
later on.
Here's an example:
% Random data
x = rand(50,1);
y = .2 + x - x.^2 + randn(size(x))/10;
scatter(x,y)
xx = linspace(0,1);
% Unconstrained fit
b1 = polyfit(x,y,3);
line(xx,polyval(b1,xx),'color','r');
% Constrained to pass through the origin
b2 = [x.^3 x.^2 x]\y;
line(xx,polyval([b2; 0],xx),'color','g');
I hope this is clear enough. Let me know if not.
-- Tom