Constructing a graph from a distance matrix
I think you're looking for RelationGraph
. It takes a list of objects to treat as vertices and a test function which determines whether two given vertices should be connected by an edge:
pts = {{0, 0}, {0, 1}, {4, 4}, {0, 2}, {1, 2}, {1, 1}};
d = 1;
RelationGraph[EuclideanDistance[#, #2] == 1 &, pts]
As of 10.3 a more idiomatic way to implement the test function would probably be
RelationGraph[EuclideanDistance /* EqualTo[d], pts]
RelationGraph
automatically makes the graph undirected if your function happens to return the same thing for both orders of every pair, and a directed graph otherwise. You can enforce either type of graph with the DirectedGraph
option (setting it either to True
or False
).
For version 9
ngF = With[{v = #, d = #2},
AdjacencyGraph[v, Outer[Boole[EuclideanDistance@## == d] &, v, v, 1], ##3]] &;
Using Martin's example, pts = {{0, 0}, {0, 1}, {4, 4}, {0, 2}, {1, 2}, {1, 1}}
ngF[pts, 1, VertexLabels -> "Name", ImagePadding -> 10]
You can also use a combination of DistanceMatrix
and Clip
to get the desired adjacency matrix:
ngF2 = AdjacencyGraph[#, Clip[DistanceMatrix[#], {1, 1} #2, {0, 0}], ##3] &;
ngF2[pts, 1, VertexSize -> Large, PlotTheme -> "VintageDiagram"]