1
votes

I've been trying to vectorize out the loops of the following code. (edited for comments)

M, N, F = 10, 50, 30
ts = np.linspace(0.001,3,M)
v = np.random.rand(N,1)
A = np.random.rand(N,N)
D = np.zeros(shape=(N,N,M)) 
for i, t in enumerate(ts):
   for x in range(0,N): 
      for y in range(x,N): 
         D[x,y,i] = np.sum( np.exp(-t * v[0:F]) * A[x,0:F] * A[y,0:F] )
         D[y,x,i] = D[x,y,i]

I've been reading other questions but can't figure out how to apply it here.

Suggestions?

1
Please add a minimal example of ts, v, and A, and F. - wwii
Do the loops work the way you want? - wwii
What are nf and F? - Khris

1 Answers

1
votes

Here's a vectorized approach using a combination of broadcasting and matrix-multiplication with np.dot -

# Get r,c indices corresponding to indices along dim-0,1 for o/p
r,c = np.triu_indices(N)
vals = (A[r,:F] * A[c,:F]).dot(np.exp(v[:nf,None]*(-ts)))

# Initialize o/p array and assign values
out = np.empty(shape=(N,N,M))
out[r,c,:] = vals
out[c,r,:] = vals