ans =
Accumulate total area between x-axis and a curve using a for loop
Show older comments
I'd like to accumulate the total area between a curve and x-axis in one go if possible using a for loop. I find points of intersection first, then based on it and x1, x2 find total area, then graph at the end. This is my code:
dy2=-x^2-2*x; x1=-3; x2=2;
poi=solve(dy2) % points of intersection of curve and x-axis
Based on the points of intersection, I'd like to calculate area with bounds of integration starting with x1, go through the points of intersections, end at x2. Can I do the code below using a loop?
A1=abs(int(dy2,x1,poi(1)));
A2=abs(int(dy2,poi(1),poi(2)));
A3=abs(int(dy2,poi(2),x2));
A_total=A1+A2+A3
Below is a graph of the shaded area.
dy1=0;
fp1 = fplot(dy1, [x1 x2]); hold on
fp2 = fplot(dy2, [x1 x2]); hold off
ylim('padded')
x1 = fp1.XData;
y1 = fp1.YData;
x2 = fp2.XData;
y2 = fp2.YData;
patch([x1 fliplr(x2)], [y1 fliplr(y2)], 'g');
hold off;
j=xline(0); set(j,'color','black','Linewidth', 1.5);
k=yline(0); set(k,'color','black','Linewidth', 1.5);
Thanks.
3 Comments
You don't need the points of intersection:
syms x
dy2=-x^2-2*x; x1=-3; x2=2;
int(abs(dy2),x1,x2)
Answers (1)
Hi @rezheen
You can compute of the total area between your curve and the x-axis using a for loop. The key is to first collect all the bounds (starting point, intersection points, and ending point), then loop through them to accumulate the absolute areas.
Here's how you can do it:
syms x
dy2 = -x^2 - 2*x;
x1 = -3;
x2 = 2;
% Find points of intersection with x-axis
poi = double(solve(dy2 == 0, x)); % returns a vector of intersection points
% Collect all integration bounds in order
bounds = [x1, sort(poi.'), x2];
% Accumulate area using a loop
A_total = 0;
for k = 1:length(bounds)-1
% Compute the definite integral over each segment
A = abs(double(int(dy2, x, bounds(k), bounds(k+1))));
A_total = A_total + A;
end
disp(['Total area = ', num2str(A_total)]);
fplot(dy2, [x1 x2], 'b', 'LineWidth', 2); hold on;
yline(0, 'k--');
for k = 1:length(bounds)-1
% Generate points for the patch
xx = linspace(bounds(k), bounds(k+1), 100);
yy = double(subs(dy2, x, xx));
fill([xx fliplr(xx)], [yy zeros(size(xx))], 'g', 'FaceAlpha', 0.3, 'EdgeColor', 'none');
end
hold off;
xlabel('x'); ylabel('y');
title('Area between curve and x-axis');
Hope this helps!
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!
