How do I obtain area under selected region on figure?

3 visualizaciones (últimos 30 días)
Pushpak Bhandari
Pushpak Bhandari el 27 de Oct. de 2021
Respondida: Abhiram el 29 de En. de 2025
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.

Respuestas (1)

Abhiram
Abhiram el 29 de En. de 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.

Categorías

Más información sobre Labels and Annotations en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by