Polynomials in MATLAB: P (X) X 3x
Polynomials in MATLAB: P (X) X 3x
Fall 2008
November 5
Polynomials in MATLAB
1 Polynomial Evaluation
A polynomial is completely known by its coefficients! For example the polynomial
p(x) = x3 − 3x2 + 1
has coefficients, beginning with the largest power, a1 = 1, a2 = −3, a3 = 0 and a4 = 1. Once these
numbers are given, it is plain that p(1) = −1 or p(4) = 17 or p(−2) = −19. MATLAB lets you
compute polynomials with the polyval command. It has the structure
polyval(coefficient vector, input data)
In our case, we could enter
>> a = [1 -3 0 1]
a =
1 -3 0 1
>> polyval(a,[1 4 -2])
ans =
-1 17 -19
As you can see, we can calculate the three values simultaneously entering a vector as the second
argument. For a plot of the curve on the interval [−1, 4] one could proceed as follows:
>> a = [1 -3 0 1]
a =
1 -3 0 1
>> x=linspace(-1,4); % generate x data
>> p = polyval(a,x); % calculate polynomial values
>> plot(x,p); grid on % graph the function
20
15
10
−5
−1 −0.5 0 0.5 1 1.5 2 2.5 3 3.5 4
2 Roots
It is known that a polynomial of degree n has exactly n, possibly complex roots. Here you have to
account for the multiplicity of the roots as well. The roots command determines the roots from
the coefficients. For our polynomial p(x) = x3 − 3x2 + 1 we find
The desired polynomial is p(x) = x4 − 7x3 + 12x2 + 4x − 16. A graph confirms the result:
80
60
40
20
−20
−2 −1 0 1 2 3 4 5
3 Polynomial Interpolation
Polynomial interpolation is built into MATLAB. The command is
It returns the coefficients of the interpolating polynomial. From class there is exactly one polynomial
of degree ≤ N − 1 which passes through N given points. MATLAB lets you approximate with lower
degree polynomials in the least squares sense. For instance if you take the degree to be one, it will
find the least squares regression line. Our usual example with the data
x 0 1 2 4
y 1 2 4 16
The vector a contains the coefficients of the polynomial, i.e. the interpolating polynomial is P4 (x) =
5 2 1 2 11
24 x − 8 x + 12 x + 1 and its value at 3 is P4 (3) = 33/4 = 8.25. For a graph of the interpolating
polynomial along with the underlying function f (x) = 2x and the data points on the interval [−1, 5]
continue as follows
35
30
25
20
15
10
−5
−1 0 1 2 3 4 5
15
10
−5
−1 0 1 2 3 4 5
4 Parametric Curves
For parametric curves (x(t), y(t) you need to display the x-values versus the y with t as a parameter.
For example, the curve x(t) = t3 and y(t) = t2 with −1 ≤ t ≤ 1 can be generated as follows:
>> t = linspace(-1,1);
>> x = polyval([1 0 0 0],t);
>> y = polyval([1 0 0],t);
>> plot(x,y), grid on, axis(’equal’)
1.2
0.8
0.6
0.4
0.2
−0.2
√
3
This, of course, is the graph of the function y = x2 .