the right sum rectangular rule in matlab

The Sum Rectangular Rule is a numerical method used to approximate definite integrals. It approximates the integral using the sum of the areas of rectangles which height is given by the function at a specific point in the interval. Here's how to code this method in MATLAB:

main.m
% Define the function to be integrated
f = @(x) exp(-x.^2);

% Define the interval of integration [a,b] and number of subintervals n
a = 0; 
b = 1;
n = 100;

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

% Evaluate the function at the left endpoint of each subinterval and sum the areas
sum_areas = 0;
for i = 1:n
    x_i = a + (i-1)*dx;
    sum_areas = sum_areas + f(x_i);
end

% Compute the approximate integral
approx_integral = dx * sum_areas;
459 chars
21 lines

In this example, we have defined the function f(x) = exp(-x^2) and are approximating the definite integral of this function over the interval [0,1] using 100 subintervals. The for loop computes the sum of the areas of each rectangle by evaluating the function at the left endpoint of each subinterval x_i and multiplying it by the width of each subinterval dx. The approximate integral is then computed by multiplying the sum of the areas by dx.

gistlibby LogSnag