simpsons rule with limits -4 and 0.4 in matlab

Here's how to use Simpson's Rule with limits -4 and 0.4 in Matlab:

main.m
% Define the function to be integrated
f = @(x) exp(x).*sin(x);

% Define the limits
a = -4;
b = 0.4;

% Define the number of subintervals (even number)
n = 10;

% Compute the width of each subinterval
h = (b - a) / n;

% Compute the summation term inside the integral
sum_odd = 0;
for k = 1:2:n-1
    xk = a + k*h;
    sum_odd = sum_odd + f(xk);
end

sum_even = 0;
for k = 2:2:n-2
    xk = a + k*h;
    sum_even = sum_even + f(xk);
end

% Compute the integral value
int_value = (h/3) * (f(a) + 4*sum_odd + 2*sum_even + f(b))

527 chars
30 lines

Explanation: First, we define the function to be integrated using an anonymous function handle. Then, we set the limits of the integration as variables a and b.

Next, we set the number of subintervals, n, and compute the width of each subinterval, h. Note that n must be an even number for Simpson's Rule to work.

We then compute the summation term inside the integral by looping through the odd-indexed and even-indexed subintervals. Finally, we compute the integral value using the formula for Simpson's Rule.

The output will be the numerical approximation of the integral value within the given limits using Simpson's Rule.

gistlibby LogSnag