Estimate area under a curve using finite approximations (lower sum with 4 rectangles of equal length)
Show older comments
Hi, I'm having trouble calculating area under a curve using lower sum with 4 rectangles, specifically the for loop. This is my code:
f= @ (x) x.^2; x1=0; x2=1; n=4;
value=0;
dx=(x2-x1)/n; % width of rectangle
for k=0:n
c=x1+k*dx;
value=value+f(c);
end
value=dx*value
Gives answer as 0.4688, but this is how the calculations should be:
A = 0*0.25 + 0.0625*0.25 + 0.25*0.25 + 0.5625*0.25 = 0.21875 % approximately
Where 1st term: dx * f(0), 2nd term: dx * f(0.25), 3rd term: dx * f(0.5), 4th term: dx * f(0.75). Thanks
Accepted Answer
More Answers (2)
f= @ (x) x.^2; x1=0; x2=1; n=4;
value=0;
dx=(x2-x1)/n; % width of rectangle
for k=0:n-1
c=x1+k*dx;
value=value+f(c);
end
value=dx*value
Try this:
f= @ (x) x.^2;
x1=0;
x2=1;
n=4;
totalArea=0;
dx=(x2-x1)/n; % width of rectangle
x = linspace(x1, x2, 500);
y = f(x);
plot(x, y, 'b-', 'LineWidth', 2)
grid on;
hold on;
xline(x1, 'Color', 'r');
xk = x1 + dx * [0 : n]
for k = 2 : length(xk)
fprintf('Processing area between %f and %f.\n', xk(k-1), xk(k))
minimumY = min(f(xk(k)) , f(xk(k-1)))
% Draw vertical lines.
line([xk(k), xk(k)], [0, f(xk(k))], 'Color', 'r', 'LineWidth', 2);
thisRectangleArea = minimumY * dx;
totalArea = totalArea + thisRectangleArea;
fprintf('Total area of boxes so far = %.5f', totalArea)
% Draw top of box.
line([xk(k-1), xk(k)], [minimumY, minimumY], 'Color', 'r', 'LineWidth', 2);
end
2 Comments
rezheen
on 12 Jun 2025
Image Analyst
on 12 Jun 2025
Edited: Image Analyst
on 12 Jun 2025
Two things I always tell people are to put in lots of comments and use descriptive variable names. Normally I would have put in lots more comments that I did in this answer. And I couldn't follow what you did immediately, though I could see something was wrong, in part because you used short cryptic variable names. I encourage everyone to use longer, more descriptive variable names so that others can understand what is being done.
Another thing to note is that the other solutions rely on the function being monotonitcally increasing (which it happens to be in this case), while mine is a more robust and general solution that looks for the minimum y value at either end of the region rather than assuming it will always be at the leftmost x value. It could be made even more general by inspecting everywhere in the region for the lowest y value rather than assuming it will always be at one of the endpoints.
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

