Xu Zhang
Xu Zhang

Reputation: 43

How to multiply a vector by an array/matrix element-wise in numpy?

I have a multidimensional array a whose shape is (32,3,5,5) and an array v with a shape of (32,). How could I multiply (i,3,5,5) with (i,) for each i using numpy other than a for-loop?

Upvotes: 4

Views: 2340

Answers (1)

Divakar
Divakar

Reputation: 221524

With a and v as the two arrays, few approaches could be suggested -

a*v[:,None,None,None]
a*v.reshape(-1, *[1]*3)
(a.T * v).T
np.einsum('i...,i->i...', a, v)

Upvotes: 2

Related Questions