Search code examples
matlabnumerical-integration

how to integrate this Function in matlab


I'm new on matlab.

How can I integrate this line of code ? ?

p2= polyfit(x,y,length(x));
from= x(1);
to= x(length(x));

I need the integration of p2.

I tried a lot with the Integration function:

 value = integral(p2,from,to);

but I got

Error using integral (line 82) First input argument must be a function handle.

Error in poly_integral (line 5)
 value = integral(p2,from,to);

Solution

  • That is because p2, in your code, is not a function. It is just a vector of coefficients. The first argument for integral needs to be handle to the function that you want to integrate.

    Judging from your code, it seems that you would want to define a function that evaluates the polynomial p2. If so, you could do something like the following example:

    % take an example set of x and y 
    x = linspace(0, pi, 1000); % uniform samples between 0 to pi
    y = sin(x); % assume, for sake of example, output is sine function of input
    
    % polynomial fit
    p2 = polyfit(x,y,4); % 4th order polynomial
    % Note that, in general, the order should be much smaller than length(x).
    % So you probably should review this part of your code as well.
    
    % define a function to evaluate the polynomial
    fn = @(x) polyval(p2, x);
    % this means: fn(x0) is same as polyval(p2, x0)
    
    % compute integral
    value = integral(fn,x(1),x(end));