Max
Max

Reputation: 15965

How to multiply a row of an array by the value stored in the corresponding row of a vector?

I have the following setup:

a = np.asarray([[1, 2, 3], [4, 5, 6]])
s = np.asarray([1, 2])

I would like to multiply a[0] * s[0] and a[1] * s[1] to get

[[1, 2, 3],
 [8, 10, 12]]

How can I do this easily? And if possible, I would like to avoid a reshape.

Upvotes: 2

Views: 60

Answers (1)

user2357112
user2357112

Reputation: 280887

a * s[:, np.newaxis]

Broadcasting goes through the shapes in the opposite direction from what you want, so we stick another axis in there. (This is very similar to a reshape.)

Upvotes: 3

Related Questions