Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply numpy array of scalars by array of vectors

Tags:

python

numpy

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?

like image 924
jterrace Avatar asked Apr 26 '11 19:04

jterrace


1 Answers

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]])
like image 148
Gökhan Sever Avatar answered Nov 07 '22 05:11

Gökhan Sever