简体   繁体   English

在矩阵和对角矩阵之间进行矩阵乘法的更快方法?

[英]The faster way to do matrix multiplication between a matrix and a diagonal matrix?

I am coding a computational package in python using numpy, in the package, I would do the matrix multiplication between an arbitrary large square matrix (eg of size 100*100) and a diagonal matrix of same size frequently. 我正在使用numpy在python中编码一个计算包,在该包中,我会经常在任意大的方阵(例如大小为100 * 100)和对等大小的对角矩阵之间进行矩阵乘法。

I have an O(n^2) method, but I think that further improvement could be made. 我有一个O(n ^ 2)方法,但是我认为可以做进一步的改进。

"""
A is of size 100*100
B is a diagonal matrix 
want to do np.dot(A,B) quickly
"""
A=np.random.rand(100,100)
diag_elements=np.random.rand(100)
B=np.diag(diag_elements)

answer1= np.dot(A,B) ###O(n^3) method, quite slow

C=np.zeros((100,100)) 
C=C+diag_elements
answer2=np.multiply(A,C) ##O(n^2) method, 3times faster for n=100

The anwer2 is O(n^2) but I think it's not good enough, because the operation C+=diag_elements are wasting 1/3 time and could be avoided possibly. anwer2是O(n ^ 2),但我认为这还不够好,因为操作C + = diag_elements浪费了1/3的时间,可以避免。

I expect that some numpy function could do the matrix multiplication more elegently and faster. 我希望一些numpy函数可以更灵活,更快地完成矩阵乘法。 Could someone help me out? 有人可以帮我吗?

为什么不简单地将A乘以对角线呢?

answer3 = np.multiply(A,diag_elements)

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

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