I have a set of data in $\mathbf{R}^3$ for which I want to construct a $k$-nearest-neighbors graph whose edges are weighted by the distance of each point to its neighbors. Is there a way to do this without reinventing the wheel, since Mathematica already contains a NearestNeighborGraph symbol? As far as I can tell, it outputs the graph I want but doesn't weight the edges by euclidean distance between the vertices.


1 Answer 1


NearestNeighborGraph uses the point coordinates as vertex names.

Therefore, if g is your NearestNeighborGraph then this will set its weights:

SetProperty[g, EdgeWeight -> EuclideanDistance @@@ EdgeList[g]]
  • $\begingroup$ Thank you! Right before you posted I figured out a worse way of doing it: g = Graph[VertexList[#], EdgeList[#], EdgeWeight -> edgeLength /@ EdgeList[#]] &@g. Would you happen to know why this makes Mathematica "forget" about the vertex locations, such that if I display it it no longer shows points in 3D? $\endgroup$
    – Diffycue
    Oct 13, 2017 at 1:41
  • 2
    $\begingroup$ Because graph no longer has 3D VertexCoordinates, you rebuild the graph from just the list of vertices and edges, and it recalculates the coordinates in 2D. A 3D point essentially becomes just a name for a vertex. $\endgroup$
    – swish
    Oct 13, 2017 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.