将数组的每个数字乘以其numpy中矩阵的对齐行?

时间:2014-02-04 14:40:43

标签: python numpy

假设我有 arr =(n项数组)和矩阵 mat = nxm矩阵。我想将arr的每个项目与矩阵垫的对齐行相乘。我该怎么办numpy?

1 个答案:

答案 0 :(得分:1)

您可以使用广播:

M = np.arange(1, 13).reshape(3, 4)
print M
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]

a = np.arange(1, 4)
print a
# [1, 2, 3]

# we broadcast a (3, 1) vector against a (3, 4) matrix
print a[...,None].shape, M.shape
# (3, 1) (3, 4)

print a[..., None] * M
# [[ 1  2  3  4]
#  [10 12 14 16]
#  [27 30 33 36]]