rk6t7
rk6t7

Reputation: 5

Faster way to implement this formula in python

n and F are 3d matrices of dimensions m * l * l, where m=5 and l=174. n is given by gamma multiplied by the square of norm 2 of Fi-Fj. Formula here
My current brute force implementation is

for k in range(0,m):
  for i in range(0,l):
    for j in range(0,l):
      dist = gamma*(np.linalg.norm(F[0][i] - F[0][j]))
      m3.append(dist)
    m2.append(m3)
  m1.append(m2)

But my program crashes. Is there an optimized way to compute this?

Upvotes: 0

Views: 27

Answers (1)

Andrey Sobolev
Andrey Sobolev

Reputation: 12693

Right now your operation is done using 3 nested slow Python-style loops. Use the power of Numpy, broadcasting along the last-but-one axis and vectorizing the operations:

n = gamma * np.sum((F[:,np.newaxis,:,:] - F[:,:,np.newaxis,:])**2, axis=-1)

Upvotes: 1

Related Questions