tryingtocode101
tryingtocode101

Reputation: 89

Numpy Array Multiplication

I couldn't seem to find this problem on stackoverflow although I'm sure someone has asked this before.

I have two numpy arrays as follows:

a = np.ones(shape = (2,10))
b = np.ones(2)

I want to multiply the first row of 10 of a by the first number in b and the second row by the second number. I can do this using lists as follows:

np.array([x*y for x,y in zip(b,a)])

I was wondering if there is a way to do this in numpy that would be a similar one liner to the list method.

I am aware I can reshape a to (1,2,10) and b to (2,1) to effectively achieve this - is this the only solution? Or is there a numpy method that can do this without manually reshaping.

Upvotes: 1

Views: 400

Answers (1)

Stack Player
Stack Player

Reputation: 1490

This might be what you are looking for:

a*np.tile(np.expand_dims(b,axis=1),(1,10))

If you want to make use of the automatic numpy broadcasting, you need to reshape b first:

np.multiply(a, b.reshape(2,1))

Upvotes: 1

Related Questions