MATLAB Project: Least Squares Solutions and Curve Fitting Name________________________
Purpose: To practice using the theory of Least Squares by calculating and plotting the Least
Squares line, quadratic curve, and cubic curve for two sets of experimental data
Prerequisite: Section 6.6
MATLAB functions used: inv, ones, norm, size, plot, hold, print, polyval, polyfit,
axis; and lsqdat from Laydata4 Toolbox
Define
11
22
1
1
1
k
k
k
nn
xx
xx
xx
X
⎡⎤
⎢⎥
⎢⎥
=⎢⎥
⎢⎥
⎣⎦
,
1
0
k
⎡⎤
⎢⎥
⎢⎥
=⎢⎥
⎢⎥
⎣⎦
β
and
1
n
y
y
⎤
⎥
=
⎥
⎥
⎦
y.
So
and y are known, and the entries of β are the unknowns. The system of equations X=βyis usually
inconsistent, but one can find an approximate solution by the Least Squares method. The Least Squares
solution will be a “best solution” in the sense that it produces a vector β for which the vector
−yβhas
smallest possible length. The length of
−yβ is called the Least Squares error.
In this project you will work with two different sets of experimental data. For each set of data,
you will calculate the Least Squares equations of degree 1, 2 and 3 and the error for each, and you will
1. Type [x0 y0] to see the vectors side by side, and examine this to familiarize yourself with the data.
Then type the following line to plot the 13 data points with * symbols, to establish scaling for the graph,
and to hold this picture so future plots will appear on same axes:
(a) Find the coefficients 0
and 1
for the Least Squares line, 10
yx
=+
. To do this, click on
the Command screen and type the following lines. These commands use the formula in the text:
X1 = [x0 ones(13,1)]
is 57.9 1 02.6yx=− (after rounding).
Calculate the error for the Least Squares line by typing err1 = norm(y0–X1*b1) and