Find local maxima with logical indexing in MATLAB

旧时模样 提交于 2020-01-14 05:12:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28988014/find-local-maxima-with-logical-indexing-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!