这是我的函数,变量track是一个列表,列表的每个元素都是n x 3
数组:
temp = np.array(np.zeros((n, n)))
for j in range(n-1):
for w in range(j + 1, n):
mindistance = np.zeros(len(tracks[j]))
for i in range(len(tracks[j])):
mindistance[i] = np.linalg.norm(min(np.fabs(np.array(tracks[w]) - tracks[j][i])))
temp[j][w]=np.sum(mindistance)/len(tracks[j])
我正在尝试计算列表数组之间的最小距离,这些距离表示空间中的3d行,但是我收到了错误:
ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()。
错误可能与调用min()
有关,但我无法解决。以下是错误追溯:
Traceback (most recent call last):
File "<ipython-input-14-7fb640816626>", line 1, in <module>
runfile('/Users/G_Laza/Desktop/functions/Main.py', wdir='/Users/G_Laza/Desktop/functions')
File "/Applications/Spyder.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 580, in runfile
execfile(filename, namespace)
File "/Users/G_Laza/Desktop/functions/Main.py", line 42, in <module>
tempA = distance_calc.dist_calc(len(subset_A), subset_A) # distance matrix calculation
File "distance_calc.py", line 23, in dist_calc
mindistance[i] = np.linalg.norm(min(np.fabs(np.array(tracks[w]) - tracks[j][i])))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
答案 0 :(得分:2)
发生错误是因为您无法确定完整数组是True
还是False
。什么是数组的布尔状态,其中所有元素都是True
但只有一个?
min
对参数进行迭代,并将每个元素与另一个元素进行比较,每个比较结果在布尔值中。迭代1-d numpy
数组会产生单个元素 - min
适用于1-d numpy数组。
>>> a
array([-4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> for thing in a:
print thing,
-4 -3 -2 -1 0 1 2 3 4
>>> min(a)
-4
>>>
迭代2-d numpy
数组会产生行。
>>> b
array([[-4, -3, -2],
[-1, 0, 1],
[ 2, 3, 4]])
>>> for thing in b:
print thing
[-4 -3 -2]
[-1 0 1]
[2 3 4]
>>>
min
因为正在比较数组和The truth value of an array with more than one element is ambiguous
而无法为二维数组工作。
>>> c
array([0, 1, 2, 3])
>>> c < 2
array([ True, True, False, False], dtype=bool)
>>> bool(c < 2)
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
bool(c < 2)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>>
>>> bool(np.array((True, True)))
Traceback (most recent call last):
File "<pyshell#75>", line 1, in <module>
bool(np.array((True, True)))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>>
>>> bool(np.array((True, False)))
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
bool(np.array((True, False)))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>>
如果您需要找到具有最小值的元素,请使用numpy.amin
或ndarray.min
方法。
>>>
>>> np.amin(b)
-4
>>> b.min()
-4
>>>