0

PYTHON

How can I compute the Euclidean distance matrix using only one for-loop. Note: only make use of Numpy, not other packages.

Thank you in advance.

This is my code using two for-loops:

m = 10
X = np.random.randint(10, size =(m,m))
D = np.zeros((m,m), dtype = int)
for i in range(0, m):
    for j in range(0, m):
        v = X[i,:] - X[j,:]
        D[i][j] = np.linalg.norm(v)
D
MaxB
  • 1
  • 2
  • Answer part 1, - Only `numpy`, - `X` is `Y` – Daniel F Nov 26 '20 at 12:22
  • Yes, this partially answers my question. Thank you for that. But do you also know how to do it with exactly one for-loop? – MaxB Nov 26 '20 at 12:44
  • there's no benefit to using a `for` loop in `numpy` when you can broadcast. The restriction of using *exactly* one `for` loop sounds suspiciously like a professor trying to keep you from seeking answers on SO. Assuming that's the case, I'll throw you a bread crumb - `np.ix_` will give you two lists of indices you can `zip` together and do in one loop. You *shouldn't*, you don't *have to*, but you *can*. – Daniel F Nov 26 '20 at 13:03
  • It is indeed an exercise the prof gave us lol. Thank you. – MaxB Nov 26 '20 at 13:32

1 Answers1

5

You don't need any loop for this.

np.linalg.norm((X[None, :, :] - X[:, None, :]), axis=-1) will give you the matrix.

Ananda
  • 2,925
  • 5
  • 22
  • 45