Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.

Topic: Peak Detection Matlab
Replies: 1   Last Post: Jan 15, 2013 1:49 PM

 Derek Goring Posts: 3,665 Registered: 12/7/04
Re: Peak Detection Matlab
Posted: Jan 15, 2013 1:49 PM

On Wednesday, January 16, 2013 5:59:10 AM UTC+13, Dara Roberts wrote:
> I have wrote some MATLAB code in relation to detecting peaks above a certain threshold(see below).The code however is detecting too many peaks for each single peak I am trying to detect(unable to upload graph). I am trying to design an algorithm to reject peaks that are too close together, lets say if they are within 100 samples. Could someone please help me with this??
>
>
>
>
>
> %Finding median over 100 values
>
> N=100;
>
> for i=1:length(testdata)-N
>
> newvalue(i+N/2)=median(testdata(i:i+N-1));
>
> end
>
>
>
>
>
> %peak detection of signal - median
>
> delta = testdata(1:length(newvalue))-newvalue';
>
> delta(1:N/2)=0; %% the first N/2 values should be set to zero;
>
>
>
>
>
> plot(delta,'g');
>
> W = delta;
>
>
>
>
>
> for j=1:length(delta);
>
> x(j) = W(j)^2;
>
> end
>
>
>
> y = sum(x)
>
>
>
> energy = sqrt((y/length(delta)))
>
>
>
> threshold = (0.7*energy) %% 0.7 is an arbitrary choice
>
> line([0 length(delta)],[threshold threshold]) %% to visualize, plot the threshold across the plot
>
>
>
> i=1
>
> for n=(delta(N/2) + 2):length(delta)-1
>
> if (delta(n)>=delta(n-1) & delta(n)>=delta(n+1) )
>
> if (delta(n)>= threshold) ;
>
>
>
> index(i)=n;
>
> i=i+1;
>
> end
>
> end
>
> end
>
>
>
>
>
>
>
> hold on
>
>
>
> plot(index,delta(index),'r+')

Instead of all those loops, do it using vectors:
S=diff(y); % Calculate the slopes
S1=S(2:end);
S2=S(1:end-1);
% Look for locations of peaks and troughs
imx=find(S1.*S2 <= 0 & S1-S2 < 0 & S2 > 0)+1;
imn=find(S1.*S2 <= 0 & S1-S2 > 0 & S1 > 0)+1;

Now you have the locations of all the peaks (and troughs)
t=[0:length(y)-1]';
plot(t,y,'b-',t(imx),y(imx),'ro',t(imn),y(imn),'gs')
So, now, you can apply your algorithm to reject peaks less than a threshold.