2

I want to find local minimas from an array or list. By the following code I can find local maximas.I know that there exists related questions, but still I just want to know, if there exists any logic by which I can use the same code for finding local minimas.

Code:

import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks

x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()
Wakil Khan
  • 134
  • 1
  • 10

1 Answers1

5

What about finding the maxima of the negative signal?

import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np

x = np.array(electrocardiogram()[2000:4000])
peaks, _ = find_peaks(-x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()
desertnaut
  • 57,590
  • 26
  • 140
  • 166
carlorop
  • 282
  • 1
  • 2
  • 8
  • 1
    Why would you negate the found Indices that find_peak returns? – couka Mar 29 '21 at 10:50
  • Did you actually run the code? Apart from what @couka correctly points out, the minus sign in `-find_peaks` will give an error (removed). – desertnaut Mar 29 '21 at 10:54
  • The current version works. the error was caused by the fact that electrocardiogram is a list – carlorop Mar 29 '21 at 12:51
  • 1
    for, x = np.array([4, 5, 6, 7, 6, 5, 4, 3, 4, 5, 6, 7, 6 ]) , above code is not working - @desertnaut – Wakil Khan Mar 29 '21 at 13:46
  • The (now removed by myself) minus sign was causing an error irrelevant of x being a list or a numpy array, and with good cause (`peaks` are array *indices*, and they cannot be negative). – desertnaut Mar 29 '21 at 13:56
  • 3
    @WakilKhan for finding the minima of [4, 5, 6, 7, 6, 5, 4, 3, 4, 5, 6, 7, 6 ], you should change `find_peaks(-x, height=0)` by `find_peaks(-x)`. If you make this change, the code works. – carlorop Mar 29 '21 at 14:21
  • @carlorop yes it worked, i changed the code as you said to change, thank you, it helped me a lot – Wakil Khan Apr 02 '21 at 04:49