Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: multiplying a 2D array by a 1D array

Let us say one has an array of 2D vectors:

v = np.array([ [1, 1], [1, 1], [1, 1], [1, 1]])
v.shape = (4, 2)

And an array of scalars:

s = np.array( [2, 2, 2, 2] )
s.shape = (4,)

I would like the result:

f(v, s) = np.array([ [2, 2], [2, 2], [2, 2], [2, 2]])

Now, executing v*s is an error. Then, what is the most efficient way to go about implementing f?

like image 264
bzm3r Avatar asked Jun 16 '14 22:06

bzm3r


1 Answers

Add a new singular dimension to the vector:

v*s[:,None]

This is equivalent to reshaping the vector as (len(s), 1). Then, the shapes of the multiplied objects will be (4,2) and (4,1), which are compatible due to NumPy broadcasting rules (corresponding dimensions are either equal to each other or equal to 1).

Note that when two operands have unequal numbers of dimensions, NumPy will insert extra singular dimensions "in front" of the operand with fewer dimensions. This would make your vector (1,4) which is incompatible with (4,2). Therefore, we explicitly specify where the extra dimensions are added, in order to make the shapes compatible.

like image 110
nneonneo Avatar answered Sep 24 '22 03:09

nneonneo