假设我有 arr =(n项数组)和矩阵 mat = nxm矩阵。我想将arr的每个项目与矩阵垫的对齐行相乘。我该怎么办numpy?
答案 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]]