How do I obtain area under selected region on figure?
4 views (last 30 days)
Show older comments
I am trying to select peak start and end points and calculate area under the curve for several regions of interest. Is there an easy way to do it quickly on the figure itself? A sample image is attached with selected (X1,Y1) and (X2,Y2) points as an example.

0 Comments
Answers (1)
Abhiram
on 29 Jan 2025
Hi Pushpak,
I see that you want to select points and calculate area under the curve for the selected region. The task can be done using the ‘ginput’ function to select the start and end points of the region of interest on the plot and calculate the area using numerical integration (such as the trapezoidal rule) using the ‘trapz’ function to calculate the area under the curve between the selected points.
An example implementation of the described method is given:
% Sample data
x = linspace(0, 10, 100);
y = sin(x) + 0.5 * x;
% Plot the data
figure;
plot(x, y, '-b', 'LineWidth', 1.5);
xlabel('X');
ylabel('Y');
title('Select Region to Calculate Area Under Curve');
grid on;
% Get two points from the user
disp('Select two points on the curve to define the region of interest.');
[x_points, ~] = ginput(2);
% Sort the points to ensure correct order
x_start = min(x_points);
x_end = max(x_points);
% Find indices of the selected points
start_index = find(x >= x_start, 1, 'first');
end_index = find(x <= x_end, 1, 'last');
% Extract the region of interest
x_region = x(start_index:end_index);
y_region = y(start_index:end_index);
% Calculate the area using the trapezoidal method
area_under_curve = trapz(x_region, y_region);
% Display the result
fprintf('The area under the curve between x = %.2f and x = %.2f is approximately %.4f.\n', x_start, x_end, area_under_curve);
% Highlight the selected region on the plot
hold on;
area(x_region, y_region, 'FaceColor', 'r', 'FaceAlpha', 0.3);
hold off;
Refer to the documentation for ‘ginput’ function and ‘trapz’ function for more details.
0 Comments
See Also
Categories
Find more on Labels and Annotations 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!