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 isccollins@math.utk.edupolyfit. Typehelp polyfitin 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];orx = [0:0.1:1];orx = [0:10]/10;y = 0.3*x + 0.8 + 0.2*randn(size(x));% randn adds some randomnessplot(x,y,'o')% plot the data using o as the markNow, compute the best linear fit and plot it:a = polyfit(x,y,1)hold on% holds the previous plotplot(x,polyval(a,x))% so that this plot will be on the same graphhold offNote: 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 ofpolyfitto 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.========================================= EXERCISES =========================================1.I've created a functionbboxwhich 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 therightbutton 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, typewhich bboxIf 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, likex = [0:100]/10;% 101 points between 0 and 10then call the function with a code numbery = bbox(x,123);% 123 is just an example codeYou 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 typebbox(x,to see the actual values.your_code,937)2.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.=================================== OPTIONAL STATISTICS ===================================There is a quantityrwhich is used to indicate the quality of the fit. The steps below computer.^{2}ypred = polyval(a,x);residuals = ypred - y;LSQerror = sum(residuals.^2);ymean = mean(y);Sy2 = sum((y-ymean).^2);rsquared = (Sy2-LSQerror)/Sy2rsquaredis close to 1 when the fit is good.