# Constructing graph of points in 3D with edges weighted by distance

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.

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

• 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? – Diffycue Oct 13 '17 at 1:41
• 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. – swish Oct 13 '17 at 1:48