简体   繁体   English

在Python中将存储在数组中的矩阵相乘

[英]Multiplying matrices that are stored in an array in Python

This may seem like a silly question, but I am a bloody newby in Python (and in programming). 这似乎是一个愚蠢的问题,但是我是Python(以及编程方面)的血腥新手。 I am running a physics simulation that involves many (~10 000) 2x2 matrices that I store in an array. 我正在运行一个物理模拟,其中涉及我存储在阵列中的许多(〜10000)2x2矩阵。 I call these matrices M and the array T in the code below. 我在下面的代码中称这些矩阵为M,数组为T。 Then I simply want to compute the product of all of these matrices. 然后,我只想计算所有这些矩阵的乘积。 This is what I came up with, but it looks ugly and it would be so much work for 10000+ 2x2 matrices. 这是我想出的,但是它看起来很丑陋,并且对于10000+ 2x2矩阵来说将是很多工作。 Is there a simpler way or an inbuilt function that I could use? 有没有我可以使用的更简单的方法或内置函数?

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]))))

Not very NumPythonic, but you could do: 不是NumPythonic,但是您可以执行以下操作:

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

Or more concisely, as suggested 或更简洁,如建议

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM