Polynomials
Polynomials
are used so commonly in algebra, geometry and math in general that
Matlab has
special
commands to deal with them.
The polynomial 2x^{4}
+ 3x^{3}
− 10x^{2} − 11x + 22 is represented in Matlab by
the array [2, 3, 10,
11, 22] (the coefficients of the polynomial are starting with the highest
power and
ending with the constant term, which means power zero). If any power is missing from the
polynomial its
coefficient must appear in the array as a zero.
Here are some examples
of the
things that Matlab can do with polynomials. I suggest you experiment
with the
code…
Roots
of a Polynomial
% Find the roots
of this
polynomial
p = [1, 2, 13, 14, 24];
r = roots(p)
% Plot the same polynomial (range 5 to 5) to
see its
roots
x = 5 : 0.1 : 5;
f = polyval(p,x);
plot(x,f)
grid on
Find
the polynomial from
the roots
If you know
that the roots of a
polynomial are 4, 3, 2, and 1, then you can find
the polynomial
(coefficients) this way:
r = [4 3 2 1];
p = poly(r)
Multiply
Polynomials
The command conv
multiplies two polynomial coefficient arrays and returns the
coefficient array of their product:
a = [1 2 1];
b = [2 2];
c = conv(a,b)
Look
(and try) carefully this result and make sure it’s correct.
Divide
Polynomials
Matlab can
do it with the command deconv,
giving
you the quotient
and the remainder
(as in synthetic division).
For
example:
% a = 2x^3 + 2x^2  2x  2
% b = 2x  2
a = [2 2 2 2];
b = [2 2];
% now divide b into a finding the quotient and
remainder
[q,
r] =
deconv(a,b)
You find quotient
q = [1 2 1] (q = x^{2}
+ 2x + 1),
and remainder
r = [0 0 0 0]
(r = 0), meaning that the division is
exact, as expected from the
example in the multiplication section…
First
Derivative
Matlab can
take a polynomial array and return the array of its derivative:
a
= [2 2 2 2] (meaning a
= 2x^{3} + 2x^{2}  2x  2)
ap
= polyder(a)
The result is ap = [6 4 2] (meaning
ap
= 6x^{2} + 4x  2)
Fitting
Data to a
Polynomial
If you have
some data in the form of arrays (x, y), Matlab can do a leastsquares fit of
a polynomial of any order you choose to this data. In this example we
will let
the data be the cosine function between 0 and pi (in 0.01 steps)
and
we’ll fit a
polynomial of order 4 to it. Then we’ll plot the two functions on the
same
figure to see how good we’re doing.
clear; clc; close all
x = 0 : 0.01 : pi;
% make a cosine function with 2% random error
on it
f = cos(x) + 0.02 * rand(1, length(x));
% fit to the data
p = polyfit(x, f, 4);
% evaluate the fit
g = polyval(p,x);
% plot data and fit together
plot(x, f,'r:', x, g,'b.')
legend('noisy data', 'fit')
grid on
Got it, right?
