0

I have a list of n polar coordinates, and a distance function which takes in two coordinates.

I want to create an n x n matrix which contains the pairwise distances under my function. I realize I probably need to use some form of vectorization with numpy but am not sure exactly how to do so.

Nezo
  • 567
  • 4
  • 18
  • The title of your question and one of its tags say "euclidean distance", but the text just says "a distance function". Are you actually trying to calculate the Euclidean distance, or just some arbitrary distance function? – BrenBarn Apr 21 '15 at 17:31

2 Answers2

1

A simple code segment is below for your reference

import numpy as np

length = 10

coord_r = np.random.rand(length)*10
coord_alpha = np.random.rand(length)*np.pi

# Repeat vector to matrix form
coord_r_X = np.tile(coord_r, [length,1])
coord_r_Y = coord_r_X.T
coord_alpha_X = np.tile(coord_alpha, [length,1])
coord_alpha_Y = coord_alpha_X.T

matDistance = np.sqrt(coord_r_X**2 + coord_r_Y**2 - 2*coord_r_X*coord_r_Y*np.cos(coord_alpha_X - coord_alpha_Y))
print matDistance
pyan
  • 3,577
  • 4
  • 23
  • 36
0

You can use scipy.spatial.distance.pdist. However, if the distance you want to calculate is the Euclidean distance, you may be better off just converting your points to rectangular coordinates, since then pdist will do the calculations quite quickly using its builtin Euclidean distance.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384