給定兩個大的numpy數組,一個用於3D點列表,另一個用於轉換矩陣列表。假設兩個列表之間存在1對1的對應關係,我正在尋找最佳方法來計算由相應矩陣變換的每個點的結果數組。numpy中的大點矩陣數組乘法
我的解決方法做,這是(在下面的示例代碼中看到「TEST4」),它工作得很好用小數組使用切片,但是失敗,因爲我的方法是如何內存浪費是:)
大型陣列import numpy as np
COUNT = 100
matrix = np.random.random_sample((3,3,)) # A single matrix
matrices = np.random.random_sample((COUNT,3,3,)) # Many matrices
point = np.random.random_sample((3,)) # A single point
points = np.random.random_sample((COUNT,3,)) # Many points
# Test 1, result of a single point multiplied by a single matrix
# This is as easy as it gets
test1 = np.dot(point,matrix)
print 'done'
# Test 2, result of a single point multiplied by many matrices
# This works well and returns a transformed point for each matrix
test2 = np.dot(point,matrices)
print 'done'
# Test 3, result of many points multiplied by a single matrix
# This works also just fine
test3 = np.dot(points,matrix)
print 'done'
# Test 4, this is the case i'm trying to solve. Assuming there's a 1-1
# correspondence between the point and matrix arrays, the result i want
# is an array of points, where each point has been transformed by it's
# corresponding matrix
test4 = np.zeros((COUNT,3))
for i in xrange(COUNT):
test4[i] = np.dot(points[i],matrices[i])
print 'done'
用一個小陣列,這工作正常。對於大數組,(COUNT = 1000000)測試#4有效,但速度相當慢。
有沒有辦法讓Test#4更快?假定不使用循環?
@WarrenWeckesser正確的,我道歉這個明顯的錯誤。我寫了兩個尖叫的孩子跑在我身邊,必須有錯誤的副本粘貼:) – Fnord