GS 2000/Math - Collins
Lab 2
Computing Least Squares Approximations in MATLAB

MATLAB has some basic commands for computing polynomials which fit
some given data using a least squares approximation.
The main command is polyfit.  Type help polyfit in MATLAB
to get further information about this command.  Below I have worked 
through some examples using this command.

First we generate some data:

x = [0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0];
x = [0:0.1:1];
x = [0:10]/10;
y = 0.3*x + 0.8 + 0.2*randn(size(x));    % randn adds some randomness
plot(x,y,'o')   % plot the data using  o  as the mark

Now, compute the best linear fit and plot it:

a = polyfit(x,y,1)
hold on                % holds the previous plot
plot(x,polyval(a,x))   % so that this plot will be on the same graph
hold off

Note: a(1) is the slope and a(2) is the intercept of the line.

To repeat this computations for a polynomial of a different degree, just
change the 1 in the call of  polyfit to the degree you want.
For example, for a cubic, it would look like:

a = polyfit(x,y,3)

All the rest of the calculations would remain the same.


I've created a function bbox which generates a random polynomial 
with some random noise added in for you to try and figure out.  To use 
it you need to save it on you computer.  To do so:

  Move the mouse over the link bbox.m, but use
  the right button and select "Save Link As ..."
  We need to save this in the folder C:MATLABR11/work, either
  click through the folders at the top or enter it directly.
  Then click on Save.  

  To check that MATLAB knows about it now, type
    which bbox
  If it says "File not Found", repeat the above proceedure, if
  you still have trouble, ask for some help.

To use this function you create a vector of x values, like

x = [0:100]/10;     % 101 points between 0 and 10

then call the function with a code number

y = bbox(x,123);    % 123 is just an example code

You can use any code > 0.  If you use a code < 1000 it will
create a random line for you to figure out.  If you use a code > 999
it will create a random polynomial of degree <11 for you to figure out.

After you think you know the coefficients of the polynomial type


to see the actual values.

Here's a data file: data file which contains some
values you can try to fit.  You can either save this file or 
just copy the values into MATLAB.


There is a quantity r which is used to indicate the
quality of the fit.  The steps below compute r2.

ypred = polyval(a,x);
residuals = ypred - y;
LSQerror = sum(residuals.^2);
ymean = mean(y);
Sy2 = sum((y-ymean).^2);
rsquared = (Sy2-LSQerror)/Sy2

rsquared is close to 1 when the fit is good.
Last Modified: June 20, 2000