How to find area under graph between two points ?
119 views (last 30 days)
Vimal Rathod on 15 Jun 2021
Edited: Vimal Rathod on 15 Jun 2021
If you would want to find area by specific points from array, you could use the indices of array to find the area.
M = trapz(A(k:l,1),A(k:l,2)); % for area between k and l index values of array A
If you would want to find area from a custom point on the line to another custom point on the line, make sure to include the array indices along with the custom point in the area.
%finding area between (x1,y1) and (x2,y2) considering these two lies on the
%k and l are the indices of array values lying in between these points.
M = trapz([x1,A(k:l,1),x2], [y1, A(K:l,2), y2]);
Hope this helps!
Scott MacKenzie on 15 Jun 2021
Edited: Scott MacKenzie on 17 Jul 2021
Assuming you want the area under the curve between two values of x (the "specific points" in your questions), here's what I put together using test data. The area under the curve is computed from x = 60 to x = 110. The area is computed two ways, using trapz and using integral. They give the same result. trapz is useful if the data are sample points gathered empirically. If you have a formula to work with, then integral can be used. It's also possible to use polyarea, although that is not demonstrated here.
% test data
x = 0:0.1:150;
y = 0.2 + sind(x) .* cosd(2*x).^2;
fun = @(x) (0.2 + sind(x) .* cosd(2*x).^2);
% organize in matrix A, as in question
A = [x' y'];
% plot total area under curve over x domain
% example "specific points" to find area between
x1 = 60;
x2 = 110;
% find indices of these points in A
idx1 = find(A(:,1) >= x1, 1);
idx2 = find(A(:,1) >= x2, 1);
% show the area under curve between x1 and x2
area(A(idx1:idx2,1), A(idx1:idx2,2), 'facecolor', [.7 .8 .9]);
% get area under curve from x1 to x2 using trapz
a1 = trapz(A(idx1:idx2,1), A(idx1:idx2,2))
% get area under curve from x1 to x2 using integral
a2 = integral(fun, x1, x2)
% print area in chart
ax = gca;
xt = (x2 + x1) / 2;
yt = 0.8 * mean(ax.YLim);
s = sprintf('Area = %.2f', a1);
text(xt, yt, s);
Output in command window: