I have to create my own function to find peaks in a signal
6 views (last 30 days)
Show older comments
Like it said in the title, I have to create my own function to find peaks. It should also output the locations of the peaks in the x and y coordinates. Can someone give me a hint? I am a beginner so I don't really have any solid ideas.
1 Comment
Voss
on 29 Dec 2021
A peak is essentially a point where the signal changes from moving up to moving down. You can use diff(y) to find the difference between adjacent samples of the signal y, and sign(diff(y)) will tell you the sign of the difference (i.e., sign == 1 -> moving up, sign == -1 -> moving down, sign == 0 -> staying the same).
Accepted Answer
Image Analyst
on 29 Dec 2021
It should be pretty easy to write your own version of islocalmax() and islocalmin() from low level commands. Just a simple for loop to scan the vector, and inside an "if" to compare the current value to the prior and later values. If the current value is greater than each of the values on either side, then log that location. I can't do it for you because you said you need to create your own function. Really trivial.
If you want to get fancier you can try duplicating findpeaks() though that would be quite an undertaking because it's a sophisticated function with lots of options.
9 Comments
Image Analyst
on 31 Dec 2021
Edited: Image Analyst
on 31 Dec 2021
@Walter Roberson I also thought of that but apparently he lucked out because of the order of the tests on the "if" line. It runs without error because of the short circuit -- it worked for that particular example vector, but it would fail if the last element was higher than the prior one.
I suggest he use my code -- it's more robust.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!