我試圖向量化一個for循環,我有一個類的方法裏面。 for循環具有以下形式:它通過一串點的迭代,並且根據一定的變量(稱爲「self.condition_met」下方)是否爲真,呼籲點一對函數,並將結果添加到列表。這裏的每個點是在列表中的一個向量的元素,即一個數據結構,它看起來像陣列([[1,2,3],[4,5,6],...])。這是有問題的功能:在numpy/scipy中矢量化循環?
def myClass:
def my_inefficient_method(self):
final_vector = []
# Assume 'my_vector' and 'my_other_vector' are defined numpy arrays
for point in all_points:
if not self.condition_met:
a = self.my_func1(point, my_vector)
b = self.my_func2(point, my_other_vector)
else:
a = self.my_func3(point, my_vector)
b = self.my_func4(point, my_other_vector)
c = a + b
final_vector.append(c)
# Choose random element from resulting vector 'final_vector'
self.condition_met設置之前my_inefficient_method被調用,因此它似乎沒有必要每次都檢查了,但我不知道如何更好地寫。由於這裏沒有破壞性操作,所以似乎我可以將整個事件重寫爲矢量化操作 - 這可能嗎?任何想法如何做到這一點?
「矢量化功能主要爲了方便而提供,而不是性能。這個實現本質上是一個for循環。「 – endolith 2012-07-12 16:47:01