9

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 try 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?

jterrace
  • 64,866
  • 22
  • 157
  • 202

1 Answers1

20
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]])
Gökhan Sever
  • 8,004
  • 13
  • 36
  • 38
  • In case (like me) you're wondering WHY this works, read https://stackoverflow.com/questions/29241056/how-does-numpy-newaxis-work-and-when-to-use-it – John Henckel Dec 28 '21 at 15:05