Skip to main content
 首页 » 编程设计

python之矩阵数组乘以向量

2025年05月04日10shihaiming

我有一个矩阵数组,我想乘以一个向量(因此矩阵中的第一个数组应该乘以向量中的第一个值,等等)。

import numpy as np 
 
# Three matrices/double arrays                                               
a = np.array([[1,2], [3, 4]]) 
b = np.array([[2,3], [4, 5]]) 
c = np.array([[3,4], [5, 6]]) 
 
# An array of matrices                                                       
d = np.array([a, b, c]) 
 
# A vector                                                                   
e = np.array([1,2,3]) 
 
# Multiply every matrix by the corresponding value in the vector             
f = [ d[i] * e[i] for i in range(len(e)) ] 
 
# Somewhat to my surpise however, this doesn't work                          
g = d * e # <-- Doesn't work 
 
# Nor does                                                                   
h = e * d # <-- Doesn't work 

所以列表理解有效,但我不知何故怀疑这是否是最有效的做事方式。

我是否忽略了一些非常简单的事情?

请您参考如下方法:

您需要对齐轴:

f = d * e[:,np.newaxis,np.newaxis] 
 
d.shape 
(3, 2, 2) 
e.shape 
(3,) 
e[:,np.newaxis,np.newaxis].shape 
(3, 1, 1) 

另一种方法是使 d 的形状为 (2,2,3),然后 e(形状为 (3,))将可以广播到 d 的形状。

您真正想要的是了解更多关于 broadcasting 的信息.

编辑:

关于你的第二个问题,就地乘法:

d *= e[:,np.newaxis,np.newaxis] 

没有创建副本。