点积与对角矩阵,不创建完整矩阵 [英] dot product with diagonal matrix, without creating it full matrix
问题描述
我想计算两个矩阵的点积,其中一个是对角矩阵.但是,我不想使用np.diag
或np.diagflat
来创建完整矩阵,而是使用直接用对角线值填充的1D数组.有什么方法或numpy操作可用于此类问题吗?
I'd like to calculate a dot product of two matrices, where one of them is a diagonal matrix. However, I don't want to use np.diag
or np.diagflat
in order to create the full matrix, but instead use the 1D array directly filled with the diagonal values. Is there any way or numpy operation which I can use for this kind of problem?
x = np.arange(9).reshape(3,3)
y = np.arange(3) # diagonal elements
z = np.dot(x, np.diag(y))
并且我要寻找的解决方案应该没有np.diag
and the solution I'm looking for should be without np.diag
z = x ??? y
推荐答案
将ndarray直接乘以向量即可. Numpy方便地假定您要将x的第n列乘以y的第n个元素.
Directly multiplying the ndarray by your vector will work. Numpy conveniently assumes that you want to multiply the nth column of x by the nth element of your y.
x = np.random.random((5, 5)
y = np.random.random(5)
diagonal_y = np.diag(y)
z = np.dot(x, diagonal_y)
np.allclose(z, x * y) # Will return True
这篇关于点积与对角矩阵,不创建完整矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!