【发布时间】:2018-07-19 06:31:18
【问题描述】:
给定两个相当大的矩阵 A、B 和一个非常复杂的函数 F,我必须计算以下表达式: The mathematical expression
我在想是否有一种有效的方法可以首先找到那些在矩阵相乘后会给出非零元素的索引 i,j,这样我就可以避免相当慢的“for 循环”。
当前工作代码
# Starting with 4 random matrices
A = np.random.randint(0,2,size=(50,50))
B = np.random.randint(0,2,size=(50,50))
C = np.random.randint(0,2,size=(50,50))
D = np.random.randint(0,2,size=(50,50))
indices []
for i in range(A.shape[0]):
for j in range(A.shape[0]):
if A[i,j] != 0:
for k in range(B.shape[1]):
if B[j,k] != 0:
for l in range(C.shape[1]):
if A[i,j]*B[j,k]*C[k,l]*D[l,i]!=0:
indices.append((i,j,k,l))
print indices
如您所见,为了获得我需要的索引,我必须使用嵌套循环(= 巨大的计算时间)。
【问题讨论】:
-
愿意分享您现有的代码吗?请看minimal reproducible example。
-
您说“矩阵乘法”,但您的表达式看起来不像矩阵乘法...您确定您的索引都正确吗?
标签: python numpy for-loop matrix indices