1
import numpy as np
x = np.random.random((3,3)) #point-set 1
y = np.random.random((3,3)) #point-set 2

neighbors_of_x = np.array([[0,1],[0],[0]])
#^^ contains indices of neighbors of points in x, in y.
#each point can have different number of neighbors in y.

#Below, for every point in x, subtract from its neighbor in y
for i in range(x.shape[0]):
  print(x[i,:] - y[neighbors_of_x[i],:])

The above is representative example; The actual point-sets may have 1000s of points. Hence, I want to "vectorize" the last 2 lines (for loop)

Is there a way to do this without a for-loop in the end, with every index i processed in parallel?

Note : Since neighbors_of_x can have varying number of indices at each i, that array is of dtype object and hence I'm unable to directly use it to select elements of y

sanjeev mk
  • 4,276
  • 6
  • 44
  • 69
  • So there's no advantage to making `neighbors_of_x` an array; it could just as well be a list of lists. Unless you can figure out a way of giving each `x[i,:]` the same number of neighbors, you are stuck with doing this calculation point by point. – hpaulj Feb 08 '19 at 05:06
  • In order to vectorize this, a first step could be to make `neighbours_of_x` an homogeneous `ndarray`. You could use this solution https://stackoverflow.com/questions/32037893/numpy-fix-array-with-rows-of-different-lengths-by-filling-the-empty-elements-wi/32043366#32043366 – yatu Feb 08 '19 at 11:44

0 Answers0