Search code examples
matlabmatrix-indexing

Find local maxima with logical indexing in MATLAB


I have used logical indexing before in MATLAB vectors for conditions like

X = X(X < 6);

Now however I would like to find local extrema using the same idea, but with "local" conditions. I would be interested in something like

X = X(X(i) > X(i-1) & X(i) > X(i + 1));

I know this wouldn't work in the first and last elements of the vector and that there are better ways to find local extrema.

This question is different from this previous one (Getting FFT peaks from data) in that I'm not specially interested in finding the maxima, but rather to be able to use logical indexing with "local" conditions referring to adjacent elements in the vector.


Solution

  • You cannot do this directly as you described. You will have to create additional data which may itself be tested logically, the output of which may be used to index into your vector. In your case, the best method would be to calculate an approximate derivative, and find downward zero-crossings of that derivative.

    x = rand(1,50);
    xDiff = diff(x);
    xZeroCross = diff(sign(xDiff));
    indexUp = find(xZeroCross>0)+1;
    indexDown = find(xZeroCross<0)+1;
    figure();
    plot(1:50,x,'r',indexDown,x(indexDown),'b*',indexUp,x(indexUp),'go');
    

    This code generates the following graph, where local-maxima are blue stars and local-minima are green circles. enter image description here