4
$\begingroup$

This:

Graph[{1 \[DirectedEdge] 2, 2 \[DirectedEdge] 3, 4 \[DirectedEdge] 1}]
AdjacencyMatrix[%] // MatrixForm

generates:

enter image description here

But, this

Graph[{1 \[DirectedEdge] 4, 6 \[DirectedEdge] 2, 3 \[DirectedEdge] 5}]
AdjacencyMatrix[%] // MatrixForm

generates:

enter image description here

Obviously, the latter one is not correct. Why?

$\endgroup$
  • 1
    $\begingroup$ Those numbers are not indices. Their indices correspond to the order they appear so effectively you have {1 -> 2, 3->4, 5->6}. $\endgroup$ – Kuba Jan 27 at 22:23
  • $\begingroup$ @Kuba: Now I understand. Thank you. $\endgroup$ – Tugrul Temel Jan 27 at 22:33
  • $\begingroup$ @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. $\endgroup$ – Tugrul Temel Jan 28 at 0:19
  • $\begingroup$ @Kuba: Maybe SparseArray offers the solution to my argument. $\endgroup$ – Tugrul Temel Jan 28 at 0:22
  • 1
    $\begingroup$ @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. $\endgroup$ – Fortsaint Jan 28 at 15:18
7
$\begingroup$

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 = AdjacencyMatrix[g1];
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

$\endgroup$
  • $\begingroup$ But in the first example taken from MMA documentation, Range[4] does not exist. I just replicated the same example with a different matrix. $\endgroup$ – Tugrul Temel Jan 27 at 22:32
  • 3
    $\begingroup$ @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. $\endgroup$ – kglr Jan 27 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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