create a function using simpsons rule in matlab

Here is an example code for implementing a function using Simpson's rule in Matlab:

main.m
function I = simpsons_rule(f,a,b,n)
% This function calculates the definite integral of a function f using 
% Simpson's rule, between the limits of integration a and b and using n 
% subintervals.
% Inputs:
% f - the function to be integrated
% a, b - the limits of integration
% n - the number of subintervals (must be an even number)
% Output:
% I - the value of the definite integral

x = linspace(a,b,n+1); % Generate the equally spaced points 
h = x(2)-x(1); % Determine the width of the subintervals

% Simpson's Rule formula
I = (h/3) * (f(x(1))+f(x(n+1)) + 4*sum(f(x(2:2:n))) + 2*sum(f(x(3:2:n-1))));
end
613 chars
18 lines

You can call the function using the command I = simpsons_rule(@(x) x.^2, 0, 1, 100), where @(x) x.^2 is the function you want to integrate. In this case, the function is x^2 and the limits of integration are 0 and 1, with 100 subintervals. The output of this function will be the value of the definite integral of the function.

gistlibby LogSnag