Sheng
Sheng

Reputation: 49

numpy 2d matrix multiplication

I have three numpy matrices x, r and r. Whose values are:

x = np.array([[4,2],
              [0,-1],
              [-2,5],
              [2,6]])

y = np.array([[1,7],
              [2,6],
              [5,2]])

r = np.array([[2,2,1],
              [2,3,1],
              [9,5,1],
              [2,0,4]])

What I'm going to do is:(it's hard to describe by words so I use code to present what I want to do)

K = r.shape[1]
D = x.shape[1]

v = np.zeros((K, D, D))
for k in range(K):
    v[k] = (r[:, k] * (x - y[k]).transpose() @ (x - y[k]))
print(v)

The final v is what I need and v is equals to

[[[103.  38.]
  [ 38. 216.]]

 [[100.  46.]
  [ 46. 184.]]

 [[111. -54.]
  [-54.  82.]]]

Is there any elegant or pythonic way to achieve this without for loops?

Thanks

Upvotes: 1

Views: 52

Answers (1)

kevinkayaks
kevinkayaks

Reputation: 2726

This should work for you:

A = x[np.newaxis,...]-y[:,np.newaxis,:] # equivalent to (x-y[k]) for all k 
B = A.swapaxes(1,2) # equivalent to (x-y[k]).transpose() for all k 
C = r.T[:,np.newaxis,:]*B # equivalent to r[:, k] * (x - y[k]).transpose()
D = C@A # equivalent to r[:, k] *(x - y[k]).transpose() @ (x - y[k])

Or in monster unreadable form

((r.T[:,np.newaxis,:]*(x[np.newaxis,...]
                       -y[:,np.newaxis,:]).swapaxes(1,2))@
                                         (x[np.newaxis,...]-y[:,np.newaxis,:]))

proof:

>>> (v==((r.T[:,np.newaxis,:]*(x[np.newaxis,...]
                   -y[:,np.newaxis,:]).swapaxes(1,2))@
                                     (x[np.newaxis,...]-y[:,np.newaxis,:]))).all()
True

Upvotes: 1

Related Questions