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 want to get the end points of an Edge of a Graph. For example see the following source,

In[1]:=gFriendShip = ExampleData[{"NetworkGraph", "Friendship"}];
In[2]:= EdgeList[gFriendShip, "Rose" \[UndirectedEdge] _]
Out[2]:={"Anna" \[UndirectedEdge] "Rose", "Ben" \[UndirectedEdge] "Rose", 
 "Rose" \[UndirectedEdge] "Nora"}

Now I want to write something like EndPoints["Rose" \[UndirectedEdge] "Nora"] (actually, EndPoints[%2] in the above example) and want to get {"Rose", "Nora"} as output.

It might be a basic thing, but I am new to Mathematica. I am using Mathematica 9.0.

share|improve this question
    
List @@ ("rob" \[UndirectedEdge] "joe") –  rasher Apr 4 at 10:50

1 Answer 1

up vote 7 down vote accepted

The FullForm of "Rose" <-> "Nora" is:

UndirectedEdge["Rose", "Nora"]

and the FullForm of the list {"Rose", "Nora"} is:

List["Rose", "Nora"]

What you want therefore is to replace the Head of the UndirectedEdge expression with List. You can do this with Apply (shorthand: @@)

List @@ UndirectedEdge["Rose", "Nora"]
(* {"Rose", "Nora"} *)

So you could define your function as:

EndPoints = List @@ # &

Then you get:

EndPoints["Rose" <-> "Nora"]
(* {"Rose", "Nora"} *)

If you want to get all the endpoint pairs from a list of edges, you could Map (shorthand: /@) the EndPoints function over the list:

EndPoints /@ EdgeList[gFriendShip, "Rose" <-> _]
(* {{"Anna", "Rose"}, {"Ben", "Rose"}, {"Rose", "Nora"}} *)

or alternatively you can use Apply at level 1 (shorthand: @@@)

List @@@ EdgeList[gFriendShip, "Rose" <-> _]
(* {{"Anna", "Rose"}, {"Ben", "Rose"}, {"Rose", "Nora"}} *)
share|improve this answer
    
thank you.. This worked perfectly.. :) –  Suman Kundu Apr 4 at 11:55

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.