multiply numpy array of scalars by array of vectors
I have a numpy array of vectors that I need to multiply by an array of scalars. For example:
>>> import numpy
>>> x = numpy.array([0.1, 0.2])
>>> y = numpy.array([[1.1,2.2,3.3],[4.4,5.5,6.6]])
I can multiply individual elements like this:
>>> x[0]*y[0]
array([ 0.11, 0.22, 0.33])
but when I t开发者_JAVA百科ry and multiply the entire arrays by each other, I get:
>>> x*y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
I think this has to do with the broadcasting rules. What's the fastest way to multiply these two arrays element-wise with numpy?
I[1]: x = np.array([0.1, 0.2])
I[2]: y = np.array([[1.1,2.2,3.3],[4.4,5.5,6.6]])
I[3]: y*x[:,np.newaxis]
O[3]:
array([[ 0.11, 0.22, 0.33],
[ 0.88, 1.1 , 1.32]])
精彩评论