Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to multiply 2 numpy array with different dimensions

I try to multiply 2 matrix x,y with shape (41) and (41,6) as it is supposed to broadcast the single matrix to every arrow in the multi-dimensions

I want to do it as :

x*y

but i get this error

ValueError: operands could not be broadcast together with shapes (41,6) (41,) 

Is there anything I miss here to make that possible ?

like image 630
Adam Avatar asked Jan 06 '23 04:01

Adam


1 Answers

Broadcasting involves 2 steps

  • give all arrays the same number of dimensions

  • expand the 1 dimensions to match the other arrays

With your inputs

(41,6) (41,)

one is 2d, the other 1d; broadcasting can change the 1d to (1, 41), but it does not automatically expand in the other direction (41,1).

(41,6) (1,41) 

Neither (41,41) or (6,41) matches the other.

So you need to change your y to (41,1) or the x to (6,41)

x.T*y
x*y[:,None]

I'm assuming, of course, that you want element by element multiplication, not the np.dot matrix product.

like image 190
hpaulj Avatar answered Jan 13 '23 13:01

hpaulj