[英]Find two local minima in python
I have a list of t values. 我有一个t值列表。 My code for finding the minima values is as follows; 我寻找最小值的代码如下:
for i in np.arange(0,499,1):
if t[i]<t[i-1] and t[i]<t[i+1] :
t_min.append(t[i])
My t values change every time and hence it may happen that one of the minima occurs at the beginning or end in that case this code would not work. 我的t值每次都会更改,因此最小值可能出现在开始或结尾处,在这种情况下此代码将无法工作。 So I need a general code which will work for any range of t values. 因此,我需要一个适用于t值范围的通用代码。
You can loop around the end using the % operator and adding one to the length of the iterator. 您可以使用%运算符在末尾循环,并在迭代器的长度上增加一个。 This treats your array 'as a circle', which is what you really want. 这会将您的数组“视为一个圆”,这正是您真正想要的。
t_min = []
for i in range(len(t)):
if t[i] < min(t[i - 1], t[(i + 1) % len(t)]):
t_min.append(t[i])
Edit: Fix the range of values i takes so that the first element isn't checked twice, thanks to @Jasper for pointing this out 编辑:修正我取值的范围,以便第一个元素不会被检查两次,这要感谢@Jasper指出
Instead of looping over the array, I suggest using scipy.signal.argrelmin which finds all local minima. 我建议不要使用scipy.signal.argrelmin来遍历数组,它会找到所有局部最小值。 You can pick two you like most from those. 您可以从中选择最喜欢的两个。
from scipy.signal import argrelmin
import numpy as np
t = np.sin(np.linspace(0, 4*np.pi, 500))
relmin = argrelmin(t)[0]
print(relmin)
This outputs [187 437]
. 输出[187 437]
。
To treat the array as wrapping around, use argrelmin(t, mode='wrap')
要将数组视为环绕,请使用argrelmin(t, mode='wrap')
Without wrap-around, argrelmin does not recognize the beginning and end of an array as candidates for local minimum. 如果没有回绕,argrelmin不会将数组的开头和结尾识别为局部最小值的候选对象。 (There are different interpretations of "local minimum": one allows the endpoints, the other does not.) If you want the endpoints to be included when the function achieves minimum there, do it like this: (对“局部最小值”有不同的解释:一种允许端点,另一种不允许端点。)如果希望在函数达到最小值时将端点包括在内,请执行以下操作:
if t[0] < t[1]:
relmin = np.append(relmin, 0)
if t[-1] < t[-2]:
relmin = np.append(relmin, len(t)-1)
Now the output is [187 437 0]
. 现在输出为[187 437 0]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.