峰值检测代码

时间:2015-07-10 12:37:48

标签: matlab signal-processing

我想计算实时信号是否在第一步中通过某些阈值。在第一步中,我想检测实际信号是否超过这些阈值(为了检测信号中的峰值)。我的Matlab代码:

k=1;  
t = 1;
l=1;

for i =1:length(sm) //sm my signal.

    if (sm(i) > 0.25)
        first(k) = i;
        k = k+1;
        if (sm(i) > 0.5)

            second(t) = i;
            t =t +1;
            if (sm(i) > 0.75)

                third(l) = i;
                l = l+1;
            end
        end
    end
end

示例:

![在此处输入图片说明] [1]

我想计算信号超过和低于三个阈值0.250.50.75的时间并返回这些窗口。基本上我在我的例子中有三个主峰。

基本上我要做的是使用fastsmooth函数和findpeaks。

signalSmoothed = fastsmooth(sm,50); plot(signalSmoothed)
[max_pk1 max_pk2] = findpeaks(signalSmoothed);
find(max_pk1 >0.5)
inversex = 1.01*max(signalSmoothed) - signalSmoothed;
[min_pk1 min_pk2]  = findpeaks(inversex);
find(min_pk1 >0.5) 

为了获得所需的峰值,哪种启发式方法?此外,被触发的图像是离线示例。一般来说,我想在线执行该技术。

编辑:我错误地定义为峰值我想要的曲线结果,即整个波浪不仅仅是最大值。

1 个答案:

答案 0 :(得分:5)

这是一个解决方案,可以获得信号sm超过阈值 0.25 0.50 0.75 的点。这些点可以转换为数据范围内的窗口,并存储在W中。最后,我们可以在同一图中轻松地绘制它们。请注意,我们需要在本地函数getwindows中进行一些检查以处理特殊情况,例如当窗口在数据范围之外启动时。在另一个窗口内检测窗口是在getwindowsspecial - 函数中完成的。

以下是代码:

function peakwindow
% generate sample data
rng(7);
sm = 2*rand(1,25)-0.5;
sm = interp1(1:length(sm),sm,1:0.01:100*length(sm));

% get points
firstup    = find(diff(sm > 0.25)==1);
secondup   = find(diff(sm > 0.50)==1);
thirdup    = find(diff(sm > 0.75)==1);
firstdown  = find(diff(sm < 0.25)==1);
seconddown = find(diff(sm < 0.50)==1);
thirddown  = find(diff(sm < 0.75)==1);

% plot the result
figure; hold on;
plot(sm,'k')
plot(firstup,sm(firstup),'*')
plot(firstdown,sm(firstdown),'*')
plot(secondup,sm(secondup),'*')
plot(seconddown,sm(seconddown),'*')
plot(thirdup,sm(thirdup),'*')
plot(thirddown,sm(thirddown),'*')

% get windows
W1 = getwindows(firstup,firstdown);
W2 = getwindows(secondup,seconddown);
W3 = getwindows(thirdup,thirddown);

% get special window
WS = getwindowsspecial(W1,W3);

% plot windows
plotwindow(W1,0.25,'r');
plotwindow(W2,0.50,'r');
plotwindow(W3,0.75,'r');
plotwindow(WS,0,'b-');


function W = getwindows(up,down)
if length(up)>1 && length(down)>1 && up(1)>down(1)
    down(1)=[]; % handle case when window begins out of bounds left
end
if length(up)<1 || length(down)<1;
    W = []; % handle if no complete window present
else
    % concatenate and handle case when a window ends out of bounds right
    W = [up(1:length(down));down]';
end


function plotwindow(W,y,lspec)
for i = 1:size(W,1)
    plot(W(i,:),[y,y],lspec)
end


% get windows of U where there is a window of H inside
function W = getwindowsspecial(U,H)
W = []; % empty matrix to begin with
for i = 1:size(U,1) % for all windows in U
    if any(H(:,1)>=U(i,1) & H(:,1)<=U(i,2))
        W = [W;U(i,:)]; % add window
    end
end

结果如下:

result1

要查看处理是否正常,我们可以在使用rng(3)初始化时绘制结果:

result2

请注意, 0.25 0.50 的窗口将从左边界开始,因此在绘制的窗口中不存在。