MATLAB: How to get a linear trendline/line of best fit with a fixed y-intercept

excelmathematicsMATLAB

I don't have access to fit, the rest of the curve fitting toolbox or any additional paid packages.
Currently I am using polyfit to produce a line through my scatter plot however based on my data I know it should go through (0,0). I know that your basic trendline is calculated using something like this LINK or using a method with squares.
I'm not sure how to adapt this to get the same functionality that you would get in Excel when you set the y-intercept equal to a constant ie: 0. Is there a matlab function for trendlines? Does someone have a nice .m that does this? Can someone explain how the linked math can be adapted to suit a fixed y-intercept?
Thanks in advance!

Best Answer

Just build the design matrix and use \ is the simple way; cfit can do it in Curve Fitting TB if you set the specific model as well.
Example:
>> x=1:10; **** ERRATUM: LINE MISSED INITIAL POSTING -dpb ****
>> y=x+rand(size(x)); plot(x,y,'*') % arbitrary data, show the data points
>> b=polyfit(x,y,1); % fit the OLS line
>> b % coefficients
b =
0.9991 0.5186
>>
>> xlim([0 10]) % expand axis to cover origin
>> yhat=polyval(b,[0 x]); % evaluate at origin and points
>> hold on; plot([0 x],yhat,'b-') % and add to plot the fitted line
Now fit without intercept term--design matrix is just the x vector without a ones column for intercept term--
>> X=x.'; % design "matrix" as column
>> b0=X\y.' % solve for slope, zero intercept
b0 =
1.0731
>> yhat0=b0*[0 x]; % evaluate over same range from origin
>> plot([0 x],yhat0,'r-') % add that line, too...
>> legend('Data points','Poly 1','Zero Intercept')
>>
Result is
You'll get a somewhat different-looking plot as the random noise won't match, of course.
If you do want the other information besides just the coefficient, then fit is probably the way to go -- again, assuming have the C-F ToolBox.
>> MZ=fit(x,y,fittype({'x'}))
MZ =
Linear model:
MZ(x) = a*x
Coefficients (with 95% confidence bounds):
a = 1.073 (1.029, 1.117)
>>
See the doc fit for the optional output arguments, etc., ...