这看起来似乎是一个愚蠢的问题,但我在Python(以及编程)中是一个血腥的新手。我正在运行一个物理模拟,它涉及我存储在一个数组中的许多(~10 000)2x2矩阵。我在下面的代码中称这些矩阵M和数组T.然后我只想计算所有这些矩阵的乘积。这就是我提出的,但它看起来很丑陋,对于10000+ 2x2矩阵来说,这将是如此多的工作。我可以使用更简单的方法还是内置的功能?
import numpy as np
#build matrix M (dont read it, just an example, doesnt matter here)
def M(k1 , k2 , x):
a = (k1 + k2) * np.exp(1j * (k2-k1) * x)
b = (k1 - k2) * np.exp(-1j * (k1 + k2) * x)
c = (k1 - k2) * np.exp(1j * (k2 + k1) * x)
d = (k1 + k2) * np.exp(-1j * (k2 - k1) * x)
M = np.array([[a , b] , [c , d]])
M *= 1. / (2. * k1)
return M
#array of test matrices T
T = np.array([M(1,2,3), M(3,3,3), M(54,3,9), M(33,11,42) ,M(12,9,5)])
#compute the matrix product of T[0] * T[1] *... * T[4]
#I originally had this line of code, which is wrong, as pointed out in the comments
#np.dot(T[0],np.dot(T[1], np.dot(T[2], np.dot(T[2],np.dot(T[3],T[4])))))
#it should be:
np.dot(T[0], np.dot(T[1], np.dot(T[2],np.dot(T[3],T[4]))))
答案 0 :(得分:1)
不是NumPythonic,但你可以这样做:
reduce(lambda x,y: np.dot(x,y), T, np.eye(2))
或者更简洁,如建议
reduce(np.dot, T, np.eye(2))