【问题标题】:Multiplying matrices that are stored in an array in Python将存储在 Python 中的数组中的矩阵相乘
【发布时间】:2013-04-04 15:33:45
【问题描述】:

这似乎是一个愚蠢的问题,但我是 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]))))

【问题讨论】:

  • 矩阵是否总是i * M for i 从 1 到某个数字?
  • 不,它们真的很复杂。如果我能弄清楚该怎么做,我实际上计划在 for 循环中即时计算它们。我应该在我的代码 sn-p 中更改它吗?也许这令人困惑。
  • 是否有理由将矩阵放入数组中?我想我可能会把它们放在一个列表中......
  • 确实,使用for 循环的列表可能会更快。
  • 好的,现在我已经完成了编辑。我将它们放入数组的原因是因为我进行数值计算。如果我将其放入列表中,我不知道它会如何影响精度。有关系吗?

标签: python arrays numpy matrix-multiplication


【解决方案1】:

不是非常 NumPythonic,但你可以这样做:

reduce(lambda x,y: np.dot(x,y), T, np.eye(2))

或者更简洁,如建议的那样

reduce(np.dot, T, np.eye(2))

【讨论】:

  • lambda x, y: np.dot(x, y) 只是np.dot
  • 我在想这似乎是reduce的工作
  • 你不需要单位矩阵,reduce(np.dot, T) 工作正常
  • 您确定这是有效的吗?也许我做错了,但我得到了不同的结果。用我上面的方法和你的 reduce() 行我: [[ 0.24112953-0.1020551j -0.22988481+0.11903133j] [-0.22988481-0.11903133j 0.24112953+0.1020551j ]] 。你的: [[ 0.29577303-0.1009189j -0.24969598+0.08683577j] [-0.24969598-0.08683577j 0.29577303+0.1009189j ]]
  • np.dot(T[0],np.dot(T[1], np.dot(T[2], np.dot(T[2],np.dot(T[3],T[4]))))) 你有两次 T[2]
猜你喜欢
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 2020-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 2020-09-03
相关资源
最近更新 更多