ENGFF012: Lesson 8: Polynomial Functions - Roots & Curve Fitting
ENGFF012: Lesson 8: Polynomial Functions - Roots & Curve Fitting
ENGFF012
Lesson 8: Polynomial Functions –
Roots & Curve fitting
2
Learning Objectives
At the end of session you should be able to:
• Use some polynomial functions – roots, poly, polyfit,
polyval
3
Roots of Polynomials
A general polynomial is an equation of the form:
𝑎𝑛 𝑥 𝑛 + 𝑎𝑛−1 𝑥 𝑛−1 +…+ 𝑎1 𝑥+ 𝑎0 = 0
Where n can be any positive integer. Naturally, MATLAB comes
with some built-in function.
Function Name Description
roots Finds the roots of any polynomial
poly Builds the coefficients of the polynomial
polyfit Calculates the least-squares fit of a data set to
a polynomial (best fits a noisy data set)
polyval Evaluate values on a polynomial (interpolation)
4
Example
Find the roots of the quadratic equation
𝑦 𝑥 = 𝑥 2 + 5𝑥 + 6 = 0
Solution
>> p=[1 5 6];
>> x = roots(p)
r=
-3.0000
-2.0000
5
Example
Find the polynomial that produce the given roots:
x=-3 and x=-2
Solution
>> x=[-3; -2];
>> p = poly(x)
r=
1 5 6
6
Exercise
Find the roots of the fourth-order polynomial
𝑦 𝑥 = 𝑥 4 + 2𝑥 3 + 𝑥 2 − 8𝑥 − 20 = 0
Solution
>> p=[1 2 1 -8 -20]
>> x = roots(p)
r=
2.0000 + 0.0000i
-1.0000 + 2.0000i
-1.0000 - 2.0000i
-2.0000 + 0.0000i
8
Example
Calculate the least-squares slope m and y-axis intercept
b (i.e. straight line) for a given set of noisy measured data
points (x,y) using the MATLAB function polyfit.
x 5 10 20 50 100
y 15 33 53 140 301
>> x=[5 10 20 50 100];
>>y=[15 33 53 140 301];
>>a=polyfit(x,y,1)
>>a=
2.9953 -2.4264
How to draw
The best straight line that fits the data is: this line?
y = 2.9953x - 2.4264
9
300
200
OR 150
a=polyfit(x,y,1)
>> x3=0:5:120;
100
50
>> y3=polyval(a,x3); 0
-50
0 20 40 60 80 100 120
Example
Suppose for the same set of data you want to find the quadratic curve that best fits
the data.
x 0.5 1 1.5 2 2.5 3 3.5 4
y 2.2 2.1 2.3 2.9 4.1 6.2 8.3 10.7
>>x=[.5 1 1.5 2 2.5 3 3.5 4];
>>y=[2.2 2.1 2.3 2.9 4.1 6.2 8.3 10.7];
>> a=polyfit(x,y,2)
a=
0.9571 -1.8452 2.9000
>>x2=0:.1:5;
>>y2=polyval(a,x2);
>>plot(x,y,’+’,x2,y2)
The quadratic equation that best fits the data is
y = 0.9571x2 -1.8452 x + 2.9000
11
Graph
18
16
14
12
10
2
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
12
Example
x 0 0.5 1 1.5 2 2.5 3 3.5
y1 1.9 2.3 3.1 4.1 6.2 8.1 11.3 14.1
y2 3.1 2.2 2 2.3 3.1 4.1 6 8.2
Given the set of data above, write a script file to perform the following:
iii. Give a title to your graph and label the x and y axis.
13
Solution
x=0:0.5:3.5;
y1=[1.9 2.3 3.1 4.1 6.2 8.1 11.3 14.1];
y2=[3.1 2.2 2 2.3 3.1 4.1 6 8.2];
a=polyfit(x,y1,2);
b=polyfit(x,y2,2);
xx=0:.1:4;
yy1=polyval(a,xx);
yy2=polyval(b,xx);
plot(x,y1,'o',x,y2,'+',xx,yy1,'r',xx,yy2,'b');
xlabel('x values');
ylabel('y values');
title('quadratic approximations');
text(2.5,polyval(a,2.5),' \leftarrow y1(x)');
text(2.5,polyval(b,2.5),' \leftarrow y2(x)');
14
quadratic approximations
18
16
14
y values 12
10
8 y1(x)
4 y2(x)
0
0 0.5 1 1.5 2 2.5 3 3.5 4
x values
15
Summary