0

If I have to arrays X (X has n rows and k columns) and Y (Y has n rows and q columns) how do I multiply the two in the vector form, such that I obtain array Z with following characteristics:

Z[0]=X[:,0]*Y
Z[1]=X[:,1]*Y
Z[2]=X[:,2]*Y
...
Z[K-1]=X[:,k-1]*Y
Z[K]=X[:,k]*Y

for c in range(X.shape[1]):
    Z[c]=X[:,c].dot(Y)
1nsg
  • 109
  • 1
  • 9

1 Answers1

2

From your description, and almost no thinking:

Z=np.einsum('nk,nq->kq',X,Y)

I could also write it with np.dot, with a transpose or two. np.dot does the matrix sum over the last dim of the 1st and 2nd to last of 2nd

Z = np.dot(X.T, Y)

=================

In [566]: n,k,q=2,3,4
In [567]: X=np.arange(n*k).reshape(n,k)
In [568]: Y=np.arange(n*q).reshape(n,q)
In [569]: Z=np.einsum('nk,nq->kq',X,Y)
In [570]: Z
Out[570]: 
array([[12, 15, 18, 21],
       [16, 21, 26, 31],
       [20, 27, 34, 41]])
In [571]: Z1=np.empty((k,q))
In [572]: Z1=np.array([X[:,c].dot(Y) for c in range(k)])
In [573]: Z1
Out[573]: 
array([[12, 15, 18, 21],
       [16, 21, 26, 31],
       [20, 27, 34, 41]])
In [574]: X.T.dot(Y)
Out[574]: 
array([[12, 15, 18, 21],
       [16, 21, 26, 31],
       [20, 27, 34, 41]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353