Accumulate total area between x-axis and a curve using a for loop

8 次查看(过去 30 天)
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 个评论
Sam Chak
Sam Chak 2025-6-24
编辑:Sam Chak 2025-6-24
@rezheen, When I plotted the graph, did I correctly understand what you wanted?
rezheen
rezheen 2025-6-24
编辑:rezheen 2025-6-24
Yes. The area is those 3 shaded regions in your graph. The answer though is 28/3 like @Torsten pointed out.

请先登录,再进行评论。

回答(1 个)

Sameer
Sameer 2025-6-30
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)]);
Total area = 9.3333
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!

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by