2011-04-26 28 views
5

我有一個numpy向量數組,我需要乘以一組標量數組。例如:乘以向量數組的num標量數組

>>> import numpy 
>>> x = numpy.array([0.1, 0.2]) 
>>> y = numpy.array([[1.1,2.2,3.3],[4.4,5.5,6.6]]) 

我可以繁殖單個元素這樣的:

>>> x[0]*y[0] 
array([ 0.11, 0.22, 0.33]) 

但當我試着和對方乘以整個數組,我得到:

>>> x*y 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: shape mismatch: objects cannot be broadcast to a single shape 

我想這與廣播規則有關。用numpy將這兩個數組元素相乘最快的方法是什麼?

回答

10
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]]) 
+0

完美,謝謝! – jterrace 2011-04-26 20:52:26