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.
$\begingroup$
$\endgroup$
Add a comment
|
1 Answer
$\begingroup$
$\endgroup$
2
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$– DiffycueCommented 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$– swishCommented Oct 13, 2017 at 1:48