# Is this a bug or my mistake?

This:

Graph[{1 \[DirectedEdge] 2, 2 \[DirectedEdge] 3, 4 \[DirectedEdge] 1}]


generates:

But, this

Graph[{1 \[DirectedEdge] 4, 6 \[DirectedEdge] 2, 3 \[DirectedEdge] 5}]


generates:

Obviously, the latter one is not correct. Why?

• Those numbers are not indices. Their indices correspond to the order they appear so effectively you have {1 -> 2, 3->4, 5->6}. – Kuba Jan 27 at 22:23
• @Kuba: Now I understand. Thank you. – Tugrul Temel Jan 27 at 22:33
• @Kuba: Although I understand what you say, it is very difficult to digest the logic behind it. Unless one has insider information about the necessity of ordering the vertices (experts like you and @kglr), one would take the example from the documentation at its face value because edges in a graph are supposed to be representing their positions in AdjacencyMatrix. That is what I was assuming until today. Thanks for the clarification. – Tugrul Temel Jan 28 at 0:19
• @Kuba: Maybe SparseArray offers the solution to my argument. – Tugrul Temel Jan 28 at 0:22
• @TugrulTemel, in graph theory you can use any symbol to label the vertexes e.g. Graph@{"alice" -> "bob"}, that is why the AdjacencyMatrix has to do with the order and not the labels. – Fortsaint Jan 28 at 15:18

Use the first argument of Graph to provide the vertex list to have the indices of AdjacencyMatrix to match the vertex indices:

g1 = Graph[Range[6], {1 \[DirectedEdge] 4, 6 \[DirectedEdge] 2, 3 \[DirectedEdge] 5}];
am1 // MatrixForm // TeXForm


$$\left( \begin{array}{cccccc} 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

Alternatively, reorder the rows and columns to match the ordering of vertex list:

g2 = Graph[{1 \[DirectedEdge] 4, 6 \[DirectedEdge] 2, 3 \[DirectedEdge] 5}];
AdjacencyMatrix[g2][[#, #]] &[Ordering@VertexList[g2]] == am1


True

• But in the first example taken from MMA documentation, Range[4] does not exist. I just replicated the same example with a different matrix. – Tugrul Temel Jan 27 at 22:32
• @TugrulTemel, since VertexList[{1 \[DirectedEdge] 2, 2 \[DirectedEdge] 3, 4 \[DirectedEdge] 1}] is {1,2,3,4} in that example there is no need to use Range[4] in the first argument or to reorder the rows and columns of the adjacency matrix. – kglr Jan 27 at 22:38