Section 9.2 Evaluating Polynomials
To evaluate a polynomial at a given x-value in MATLAB, use the polyval function,
y = polyval(p,x)
Here, \(p\) is a row vector of polynomial coefficients (that stores the desired polynomial), and \(x\) is/are the value(s) of the independent variable at which we wish to evaluate p. Here are some examples. Suppose we wanted to evaluate the polynomial \(p(x) = x^2 - 1\) at various x-values. We’d first define:
>> p = [1 0 -1];
With this, we can evaluate:
>> y = polyval(p,5)
y =
24
Alternatively, we can use a variable at which to evaluate p:
>> x = 5; >> y = polyval(p,x) >>
y = 24
Just like other functions in MATLAB, the
polyval
function is vectorized. This means that you can evaluate a polynomial at multiple x-values at once:>> x = [1 3 5]; >> y = polyval(p,x) >>
y = 0 8 24
Can you guess how we will make use of this to display the graph of a polynomial?