# How to calculate the area under two peaks?

6 views (last 30 days)
Sam on 15 Aug 2022
Commented: Sam on 15 Aug 2022
I am trying to calculate the area under two peaks before and after background subtraction.
My code currently looks like this (example data is attached, in .txt form):
%Import the data in from excel
num = importdata('i22-569960_example.dat')
%Smooth data
data = smoothdata(num)
%Calculate area of full graph
x = data(:,1);
y = data(:,2);
[~,imax] = max(y);
area_tot = trapz(x,y)
%Baseline correction
B = [x([1 end]) ones(2,1)] \ y([1 end]);
ydt = [x ones(size(y))] * B;
ybc = y-ydt; % Baseline Corrected
figure
plot(x, ybc)
grid
%Calculate area under peaks
[pks, locs, w, p] = findpeaks(x, ybc)
As you can see, I have managed to calculate the total area under the peaks, however I am having issues calculating the area under the peak with findpeaks following this. This is the error code:
Error using findpeaks
Expected X to be strictly increasing.
Error in findpeaks>parse_inputs (line 236)
validateattributes(Xin1,{'numeric'},{'real','finite','vector','increasing'},'findpeaks','X');
Error in findpeaks (line 135)
= parse_inputs(isInMATLAB,Yin,varargin{:});
Error in OrientationScript (line 25)
[pks, locs, w, p] = findpeaks(x, ybc)
I'm not quite sure why findpeaks won't work with my data, as my X axis is increasing . I have also looked at using trapz, but I am less familar with that.

Walter Roberson on 15 Aug 2022
y goes before x in findpeaks() call.
data = smoothdata(num);
x = data(:,1);
y = data(:,2);
issorted(x)
ans = logical
1
[~,imax] = max(y);
area_tot = trapz(x,y)
area_tot = 2.4505e+04
%Baseline correction
B = [x([1 end]) ones(2,1)] \ y([1 end]);
ydt = [x ones(size(y))] * B;
ybc = y-ydt; % Baseline Corrected
figure
plot(x, ybc)
grid %Calculate area under peaks
[pks, locs, w, p] = findpeaks(ybc, x)
pks = 2×1
36.6826 36.0098
locs = 2×1
77.7273 265.9091
w = 2×1
97.9142 83.9262
p = 2×1
36.6826 33.3195
##### 1 CommentShowHide None
Sam on 15 Aug 2022
Oh wow, that was a very easy fix! How on earth did I miss that?!
Thank you so much!

R2022a

### Community Treasure Hunt

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

Start Hunting!