Search code examples
functionmatlabnumerical-integrationpolynomials

How to integrate p(x)*f(x) where p(x) is a polynomial and f(x) is a function? MATLAB


I want to integrate p(x)*f(x) where p(x) is a polynomial and f(x) is a function. I am working in MATLAB. I have the coefficients of the polynomial in a vector.

p=[2,3,4,5];
funct=@(x) xˆ2;

I know how to integrate the function by itself, as well as how to integrate the polynomial by itself. However, I just can't find any info on how to take the integral of the product.

Here is what I tried:

p2=poly2sym(p)
integral(funct*p2,-1,1)

but p2 is not a function handle.

Help is appreciated!


Solution

  • Yes, p2 is not a function handle – it's a symbolic expression, but integral performs numerical integration and requires a function handle that returns floating point values. Even if p2 was a function handle, multiply function handles (e.g., funct*p2) is not valid. Additionally, funct needs to be vectorized.

    Instead of poly2sym, you can evaluate your integral numerically with polyval like this:

    p = [2,3,4,5];
    funct = @(x)x.^2;                  % use element-wise power to vectorize
    p2 = @(x)polyval(p,x);
    integral(@(x)funct(x).*p2(x),-1,1) % evaluate two handles into one
    

    which returns 4.533333333333333. Or you could compute this particular integral symbolically using int:

    p = [2,3,4,5];
    syms x;
    funct = x^2;
    p2 = poly2sym(p,x);
    int(funct*p2,x,-1,1)
    

    which returns the exact rational value of 68/15 (use vpa or double to convert to decimal or floating point, respectively).