Home > Net >  fastest way to calculate resulting matrix numpy
fastest way to calculate resulting matrix numpy

Time:10-02

Given a 2-d numpy array X of dimension [m,m] and a 1-d array Y of length m, I wish to calculate a resulting 2-d matrix, P also of dimension [m,m], whose [i,j] element is obtained using the following operation:

P[i][j] = Y[i] * Y[j] * np.dot(X[i],X[j]) 

Is there a faster way rather than applying a nested for loop?

CodePudding user response:

You can use:

P = Y*Y[:, None]*np.dot(X, X.T)

example:

>>> X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> Y = np.array([10, 11, 12])
>>> P = Y*Y[:, None]*np.dot(X, X.T)
>>> P
array([[ 1400,  3520,  6000],
       [ 3520,  9317, 16104],
       [ 6000, 16104, 27936]])
  • Related