5

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?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This works! Could you explain the rationale behind why this works?
@user89: added an explanation.
this syntax with None is the same as with np.newaxis instead of the None, (though personally i prefer the None over the np.newaxis too).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.