book 1
What is a polynomial least square approximation? Use Problem 1 in Week 8, Lesson 8 attachment to explain. Give as many details as possible.
Given x(i) and y(i), compute the least squares
polynomial of degree 2 and calculate the total error
for the polynomial using MATLAB.
To calculate Px
i
you need a
i
. In order to use the
formula below to calculate a
i
, you need: x
i
, y
i
, x
i
2
, sum
of x
i
, the square of sum of x
i
, sum of y
i,
x
i
*y
i
, sum of
x
i
*y
i
,
>> x = [1 2 3]'
% create a 1x3 matrix for x(i)
x =
1
2
3
>> y= [4 5 6]'
% create a 1x3 matrix for y(i)
y =
4
5
6
>> xsq = x.^2
% square elements of a x matrix
xsq =
1
4
9
>> xy = x.*y
% Multiply elements row by row from matrix x,y
xy =
4
10
18
>> Z = [x,y,xsq,xy]
% concatenate matrices into Z matrix
Z =
1 4 1 4
2 5 4 10
3 6 9 18
>> v = sum(Z)
% each column of v corresponds to sum of x,
sum of y, sum of x square, sum of x*y
v =
6 15 14 32
% a
0
=
∑
푚
푖
=
1
푥
푖
2
∑
푚
푖
=
1
푦
푖
‒
∑
푚
푖
=
1
푥
푖
푦
푖
∑
푚
푖
=
1
푥
푖
푚
(
∑
푚
푖
=
1
푥
푖
2
)
‒
(
∑
푚
푖
=
1
푥
푖
)
2
>> a0 = ((v(3) * v(2)) - (v(4)*v(1)))/(length(x)*v(3)- (v(1).^2))
a0 =
3
% a
1
=
푚
(
∑
푚
푖
=
1
푥
푖
푦
푖
)
‒
∑
푚
푖
=
1
푥
푖
∑
푚
푖
=
1
푦
푖
푚
(
∑
푚
푖
=
1
푥
푖
2
)
‒
(
∑
푚
푖
=
1
푥
푖
)
2
>> a1 = ((length(x)* v(4)) - (v(1)*v(2))) / (length(x)*v(3)- (v(1).^2))
a1 =
1
% Polynomial P(x) = a
1
x
i
+ a
0
>> P = @(x) x+3
% P(x) x + 3
P =
function_handle with value:
@(x)x+3
>> Pxi = [P(1) P(2) P(3)]'
% Write P(x) in form of 1x3 matrix
Pxi =
4
5
6
Another easy way to calculate Pxi is to use the matrix “x” instead of writing each value of x.
>>Pxi = x.*a1+a0
To calculate the total Error:
E =
∑
푚
푖
=
1
(
푦
푖
‒
푃푛
(
푥
푖
))
2
>> yiPxi = [y,Pxi]
% Concatenate yi and Pxi before subtract
yiPxi =
4 4
5 5
6 6
>> error = -diff(yiPxi,1,2)
% Calculate the difference yi-Pxi
error =
0
0
0
>> errorSq = error.^2
% Calculate the square of the diff. yi-Pxi
errorSq =
0
0
0
>> E = sum(errorSq)
% Calculate the sum of the square to get E
E = 0