Skip to main content

Section 15.4 Examples and questions

These are additional examples for reviewing the topic we have covered. When reading each example, try to find your own solution before clicking “Answer”. There are also questions for reviewing the concepts of this section.

Recursively find the coefficients and roots of Legendre polynomials of degrees up to 10. Plot all of them on the interval \([-1, 1]\text{.}\) The polynomials should be represented as vectors of coefficients, for example q = [1 0] represents \(q(x) = 1x+0 = x\text{.}\) Once the coefficients are computed, one can use polyval(q, x) to evaluate the polynomial at every point of vector x, so that, for example, plot(x, polyval(q, x)) can be used to plot it.

Answer

We have to start with [1] and [1 0] which represent \(1\) and \(x\text{.}\) Once a vector of coefficients q exists, one can use concatenation [q 0] to shift the coefficients to the left, representing multiplication by \(x\text{.}\)

p = [1];
q = [1 0];
x = linspace(-1, 1, 1000);
hold on
plot(x, polyval(p, x), x, polyval(q, x));

for n = 1:9
    r = ((2*n+1)*[q 0] - n*[0 0 p])/(n+1);
    p = q;
    q = r;
    disp(r);
    plot(x, polyval(r, x))
end
hold off

The loop runs up to \(n=9\) because the polynomial being computed has degree \(m+1\text{.}\) In the loop, q is a polynomial of degree \(n\) and p is a polynomial of degree \(n - 1\text{.}\) Concatenation [0 0 p] adds zero terms to the latter polynomial; this does not change it mathematically but makes it possible to do vector addition of coefficients.

Adapt the code in Example 15.4.1 to find and plot the roots of Legendre polynomials of degrees 2 through 10.

Answer

The command roots can be used to find the roots. A convenient way to plot them so that one can tell the difference between different degrees is to use the y-coordinate for the degree.

p = [1];
q = [1 0];
hold on
for n = 1:9
    r = ((2*n+1)*[q 0] - n*[0 0 p])/(n+1);
    p = q;
    q = r;
    plot(roots(r), n+1, 'b*');
end
hold off