Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: multiply arrays rowwise

Tags:

python

numpy

I have those arrays:

a = np.array([      [1,2],      [3,4],      [5,6],      [7,8]])  b = np.array([1,2,3,4]) 

and I want them to multiply like so:

[[1*1, 2*1], [3*2, 4*2], [5*3, 6*3], [7*4, 8*4]] 

... basically out[i] = a[i] * b[i], where a[i].shape is (2,) and b[i] then is a scalar.

What's the trick? np.multiply seems not to work:

>>> np.multiply(a, b) ValueError: operands could not be broadcast together with shapes (4,2) (4) 
like image 786
wal-o-mat Avatar asked Apr 08 '14 10:04

wal-o-mat


People also ask

What happens when you multiply NumPy arrays?

multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.

How do you multiply a NumPy array by a scalar?

Method 1: Multiply NumPy array by a scalar using the * operator. The first method to multiply the NumPy array is the use of the ' * ' operator. It will directly multiply all the elements of the NumPy array whether it is a Single Dimensional or Multi-Dimensional array.

Is NP multiply same as *?

The * operator can be used as a shorthand for np. multiply on ndarrays.


1 Answers

add an axis to b:

>>> np.multiply(a, b[:, np.newaxis]) array([[ 1,  2],        [ 6,  8],        [15, 18],        [28, 32]]) 
like image 96
behzad.nouri Avatar answered Sep 19 '22 13:09

behzad.nouri