不同大小矩阵相乘的Pythonic方法
我有一个1800乘1800的矩阵(叫做Rho),我在用循环来计算一个参数,像这样:
for k in range(10):
R = (-1)**k * binom(n-k, k) * binom(n - 2*k, (n-m)//2 - k) * np.power(Rho, (n - 2*k))
但是这个循环真的很耗时间。所以,我在想能不能用矩阵的方式来写,像这样:
R_array = np.zeros(10)
k = np.arange(10)
R_array = (-1)**k * binom(n-k, k) * binom(n - 2*k, (n-m)//2 - k) * np.power(Rho, (n - 2*k))
这里的n和m是常量,比如说m=10,n=6。这样可以去掉for
循环。但是因为涉及到矩阵Rho
,最后一部分,也就是np.power(Rho, (n - 2*k))
就出错了!
所以,有没有人知道怎么解决这个问题?
我尝试了不同的矩阵写法,但都没有成功!
2 个回答
-1
我不太确定你是否能完全去掉for循环,但你可以试试“向量化”的方法。
# Vectorize parts of your calculations that don't involve powers of Rho
k = np.arange(max(int((n-m)/2 + 1), 10))
multipliers = (-1)**k * binom(n-k, k) * binom(n - 2*k, (n-m)//2 - k)
# Initialize an array to store the results
R_results = np.zeros((10, 1800, 1800))
# Loop over the elements in 'multipliers', but apply each to the whole matrix
for i, multiplier in enumerate(multipliers):
if i >= 10: # Assuming you want to stop at 10 like in your original loop
break
R_results[i] = multiplier * np.power(Rho, (n - 2*k[i]))
# If you need a cumulative result, you can sum over the first axis:
R_final = np.sum(R_results, axis=0)
我觉得一般来说,对大矩阵进行计算是比较耗时间的。
0
你的循环耗时很长,因为你不能通过已经计算过的低次幂来计算更高的幂。也就是说,
for k in range(10):
R = f(k) * np.power(Rho, (n - 2*k))
计算
big_rho = np.identity(...)
rho_squared = np.power(rho, 2)
for k in reversed(range(10)):
big_rho *= rho_squared
R = f(k) * big_rho