Composite Trapezoid Rule

In numerical analysis, the trapezoidal rule is used for approximation of a definite integral. The code here is a general purpose code for any equation. [1]


function integral = trapezoid(f, a, b, n)

   x = (b-a)/n;
   result = 0.5*f(a) + 0.5*f(b);
   for i = 1:(n-1)
       result = result + f(a + i*x);
   integral = x*result;


f is the equation, a is the lower limit, b is the upper limit, and n is the number of trapezoids or number of integration points.