Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am looking to draw a graph knowing a simple adjacency representation of the graph like:

 A = {{1, 3}, {2, 3}, {3, 4, 5}, {4, 5}, {5}}

Where A is my Adjacency List. I was thinking I could use Graph[] and maybe some kind of pattern matching:

 Graph[{_\[DirectedEdge]_}]

I am also not familiar with patterns in mathematica (the "_" that gets used a lot but has been hard for me to understand).

share|improve this question
1  
Are you missing one sub-list? You got 5 vertexes but 4 sub-lists. –  Vitaliy Kaurov Mar 25 '13 at 22:34
    
@VitaliyKaurov you are 100% correct. I fixed it. –  Matthew Kemnetz Mar 25 '13 at 22:48
add comment

1 Answer

up vote 5 down vote accepted

Adjacency list "...is a collection of unordered lists, one for each vertex in the graph. Each list describes the set of neighbors of its vertex."

I will modify your list slightly to have a bit more interesting graph:

A = {{1, 3}, {2, 3}, {3, 4, 5}, {4, 5}, {1, 2, 4, 3}};

Then define a function:

el[x_] := Flatten[MapIndexed[Thread[First[#2] -> #1] &, x]]

And build your graph:

Graph[el[A], GraphStyle -> "SmallNetwork", GraphLayout -> "LayeredDigraphEmbedding"]

enter image description here

share|improve this answer
    
My only issue is that my adjacency lists are defined such that the first element is the vertex and each subsequent element represents the edges. This definition would remove all of the 1-cycles in your implementation. –  Matthew Kemnetz Mar 25 '13 at 23:04
    
This is also a great example of neat mathematica programming but I don't understand what you are doing. Could you explain a little of what is going on? –  Matthew Kemnetz Mar 25 '13 at 23:05
    
if first element in your list is the starting vertex, then you could do Graph[Flatten[Thread[#1 [DirectedEdge] {##2}] & @@@ A]] –  halmir Mar 26 '13 at 1:56
    
@MatthewKemnetz you would need to look up in the documentation how the functions work. Start with MapIndexed, then Thread, then Flatten. The main idea here is that you are building a Graph out of list of edges. To construct list of edges you need to connect index of the sub-list (vertex) with its elements (neighbor vertexes) by an edge ->. That what MapIndexed do. –  Vitaliy Kaurov Mar 26 '13 at 4:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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