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?

1 Answer 1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

In case (like me) you're wondering WHY this works, read stackoverflow.com/questions/29241056/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.