通过数组数组乘以NumPy标量数组的快速方法

时间:2017-09-21 19:14:22

标签: python python-3.x numpy numpy-broadcasting elementwise-operations

这样进行乘法的最简洁方法是什么?

# c's are scalars (or arrays like A's in general)
x = np.array([c1, c2, c3])
# A's are NumPy arrays
M = np.array([A1, A2, A3])

获取

x*M = [c1*A1, c2*A2, c3*A3]

c是标量,A是NumPy数值多维数组(比方说,矩阵)。

示例代码:

x = np.array([1,2,3])
A = np.random.rand(2,2)
M = np.array([A,A,A])

2 个答案:

答案 0 :(得分:2)

如果M是原始数字类型(即不是对象)的numpy数组,为了利用numpy广播,您可以向x添加维度,使其具有与{{1}相同的维数然后,元素乘法应该起作用:

M
x.reshape((-1,) + (1,)*(M.ndim - 1)) * M

2D案例:

x = np.array([1,2,3])

3D案例:

M = np.arange(12).reshape(3,4)    
x.reshape((-1,) + (1,)*(M.ndim - 1)) * M
#array([[ 0,  1,  2,  3],
#       [ 8, 10, 12, 14],
#       [24, 27, 30, 33]])

答案 1 :(得分:-1)

product = [x [i] * M [i] for i in range(len(x))]