Python: pairwise distances between observations in n-dimensional space

Suppose we have an n-dimensional vector v = (v[0], …, v[N-1]) and we would like to compute a 2D matrix D whose element D[i,j] denotes the distance between v[i] and v[j]. A simple solution combines 2 scipy.spatial.distance functions squareform and pdist. The function pdist computes pairwise distances but the return value is a 1D vector without any duplicate elements. This means that the 1D vector does not have the diagonal elements D[i,i]. So, we need to convert the 1D vector to 1 2D matrix form by using the function squareform.

D = scipy.spatial.distance.squareform(scipy.spatial.distance.pdist(v))


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s