在我使用的代码中(用 python 编写,但也标记为 matlab,因为 numpy 非常接近,如果需要我可以使用它),我们使用传递矩阵方法来计算物理系统的属性。即对于初始位置的粒子,我们将最终位置计算为
# The list of matrices
Ms = [M1, M2, M3, ..., Mn]
# Start with the identity matrix
result = np.identity(2)
# Multiply the matrices
for M in Ms:
result = M @ result
我的问题是:有没有加快矩阵乘法步骤的聪明方法? 或者,我也会对使用 numpy voodoo 节省时间的不太聪明的方法感兴趣。
不幸的是,这些矩阵不会交换,所以我不能取对数、求和,然后取矩阵指数,我认为这会更快。
编辑: 矩阵生成如下:
# Calculate the constant matrices and edge matrices
Ms = get_M_const(E, B, gammas[:-1], delta_z)
rising_Ms = np.concatenate((np.array([[[1.0,], [0.0,]], [[0.0,], [1.0,]]]), get_M_edge(E[1:], gammas[1:-1], 'rising')), axis=2)
falling_Ms = get_M_edge(E, gammas[1:], 'falling')
# Interleave the arrays
c = np.empty((2,2, Ms.shape[-1]+rising_Ms.shape[-1]+falling_Ms.shape[-1],), dtype=Ms.dtype)
c[:,:,0::3] = rising_Ms
c[:,:,1::3] = Ms
c[:,:,2::3] = falling_Ms
从技术上讲,存在三种不同类型的矩阵我使用 numpy 函数计算以利用矢量化例程。变量E,B和gammas是形状 (n) 的 numpy 数组,delta_z只是一个数字。这些函数返回 (2,2,n) 数组,然后我将其交错以获得相乘的完整 (2,2,3n) 矩阵数组。
我想我在第一个代码块中通过将矩阵列为本机 python 列表来简化我的代码。剩下的就是我如何执行矩阵乘法。我在转置的元素上运行 for 循环c。