I'm trying to select peaks from a signal in a sort of "windowed" sense, and the function that does this is currently a big bottleneck, so I'd like to speed it up. Here is an example of what I want to do:
N=500; % more like 1e5 or 1e6 in my application thresh = 1.8; W = 25; x = randn(1,N);
Ndets = 0; n=1; while n<N-W if abs(x(n)) > thresh Ndets = Ndets+1; k1(Ndets) = n; n = n+W; else n = n+1; end end k1 = k1(1:Ndets);
This loop selects maxima in abs(x) separated by at least W samples, and it does so in a particular way. This is the exact algorithm that I want to use, but using that loop is slow, and gets worse as threshold increases. I found another way to do this, only looping over samples that exceed the threshold. This is usually faster, but it is much worse for LOW thresholds, and regardless, it still relies on looping.
Can anyone see a way to speed this up? Vectorizing seems difficult because of the way that the loop depends on previous results, but I don't know if that means it's impossible or not. There may be a way to do this by looping over the "window index", so that the loop only executes at most W times, rather than at most N times, but I can't figure that out.
If I can't speed it up for the general case, speeding it up for the case of higher thresholds (and therefore less peaks) is acceptable as well.