I am Charmie

メモとログ

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))