Here's an implementation of Simpson's 1/3 rule in MATLAB:
main.m494 chars19 lines
This function takes four inputs: a function handle to the integrand fun
, the lower and upper limits of integration a
and b
, and the number of subintervals n
. It first checks if n
is even, and throws an error otherwise.
Then, it creates the array of points x
that split the interval [a,b]
into n
subintervals (with n+1
points). It evaluates the integrand at these points to obtain the array y
.
Finally, it applies Simpson's 1/3 rule to compute the approximation for the integral. The formula is applied directly using array operations, with special treatment for the first and last points.
Here's an example of how to use this function:
main.m131 chars6 lines
gistlibby LogSnag