在数组中寻找最小值 [英] Finding minimum in an array
问题描述
我想在idx 2-7之间找到最小的"y"数字,但是我做错了什么. 目前它打印x = 0.02和y = 101,我希望它打印出x = 0.05和y = 104. 即使我将"idx = 3"更改为更高的数字,也不会更改.
i want to find the smallest "y" number between idx 2-7, but theres something im not doing right. For the moment it prints x = 0.02 and y = 101, i want it to print out x = 0.05 and y = 104. Even if i change the "idx = 3" to a higher number nothing changes.
我已将其从max更改为min,因此仍然有人说max,但是只要"y [:idx] .argmin()"为min,我认为这并不重要吗?
I have changed it from max to min, therefor some still say max, but i dont think that matters as long as " y[:idx].argmin()" is min?
import numpy as np
# idx: 0 1 2 3 4 5 6 7
x = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08]) # strain
y = np.array([ 110, 101, 110, 106, 102, 104, 112, 115]) # load
idx = 3
cutoff = 0.08
while x[idx] < cutoff:
idx = idx + 1
max_idx = y[:idx].argmin()
max_x = x[max_idx]
max_y = y[max_idx]
print (max_x)
print (max_y)
推荐答案
y[:idx]
是第一个idx
值.您要y[2:]
.
此外,min_idx = y[2:].argmin()
还提供关于y[2:]
的最小索引.
因此,相对于y
的最小索引应为2+min_idx
.
Also, min_idx = y[2:].argmin()
gives you the min index with respect to y[2:]
.
So the min index with respect to y
would be 2+min_idx
.
import numpy as np
# idx: 0 1 2 3 4 5 6 7
x = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08]) # strain
y = np.array([ 110, 101, 110, 106, 102, 104, 112, 115]) # load
min_idx = y[2:].argmin()
min_x = x[2+min_idx]
min_y = y[2+min_idx]
print (min_x)
# 0.05
print (min_y)
# 102
如果您希望将注意力集中在x> = 0.03并且x <0.07,然后使用布尔掩码将x
和y
限制为这些值:
If you wish to restrict attention to those values of x for which x >= 0.03 and x < 0.07, then use a boolean mask to restrict x
and y
to those values:
import numpy as np
# idx: 0 1 2 3 4 5 6 7
x = np.array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08]) # strain
y = np.array([ 110, 101, 110, 106, 102, 104, 112, 115]) # load
lower, upper = 0.03, 0.07
mask = (x >= lower) & (x < 0.07)
# array([False, False, True, True, True, True, False, False], dtype=bool)
# select those values of x and y
masked_y = y[mask]
masked_x = x[mask]
# find the min index with respect to masked_y
min_idx = masked_y.argmin()
# find the values of x and y restricted to the mask, having the min y value
min_x = masked_x[min_idx]
min_y = masked_y[min_idx]
print (min_x)
# 0.05
print (min_y)
# 102
这篇关于在数组中寻找最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!