MATLAB: How to integrate area under peak

area under peak

For my events, I have data points for y-axis. As a sample, I have attached a text file containing datapoints for one of my events. As I have shown in figure, I want to integrate area of each region displayed in various colors. I can find start and end boundary for a region using findchangepts function. However, it provides start and end points few points away from the exact location. Could you please help me with this? Also, if someone can suggest any other function to find start and end boundary, would be a great help.
I have tried, trapz(y); but didn't work the way I want.

Best Answer

Try this:
D = load('data for peak area.txt');
idx = D >= 0.28;
chg = [find(diff(idx ~= 0)); numel(D)];
chg(1) = 1;
for k1 = 1:numel(chg)-1
segment_area(k1) = trapz(chg(k1:k1+1), D(chg(k1:k1+1)));
Q1(:,k1) = chg([k1 k1+1]);
Q2(:,k1) = D(chg([k1 k1+1]));
end
figure(1)
plot(D)
hold on
plot(Q1, Q2, 'pg')
hold off
grid
area_text = regexp(sprintf('%.2f\n', segment_area), '\n', 'split');
text(mean(Q1), ones(size(segment_area))*0.12, area_text(1:end-1), 'HorizontalAlignment','center')