3
$\begingroup$

I have the following code

rand = {1, 2, 3};
el = EdgeList[CompleteGraph[5]]
g = CompleteGraph[5, 
  EdgeLabels -> Table[el[[i]] -> RandomChoice[rand], {i, Length[el]}]]

What I want is to get the labels of each edge of my graph in a list. Is there a way to do it?

$\endgroup$
1
  • $\begingroup$ The thing is I want to input two vertices and get the label of the edge between them $\endgroup$
    – mclord
    Dec 17, 2021 at 15:21

2 Answers 2

1
$\begingroup$

You can use PropertyValue (and/or AnnotationValue in versions 12.1+) as follows:

ClearAll[edgeLabel]
edgeLabel[g_, {a_, b_}] := PropertyValue[{g, UndirectedEdge[a, b]}, EdgeLabels]

Examples:

SeedRandom[7];
cg = CompleteGraph[5,
  EdgeLabels -> {_ :> RandomChoice[{1, 2, 3}]}, 
  VertexLabels -> Placed["Name", Center], VertexSize -> Medium]

enter image description here

Grid[Transpose[{Defer /@ Unevaluated @ #, #} & @
   Unevaluated @ {edgeLabel[cg, {1, 5}], edgeLabel[cg, {5, 1}], 
     edgeLabel[cg, {5, 3}], edgeLabel[cg, {3, 5}], 
     edgeLabel[cg, {2, 6}], edgeLabel[cg, {2, 2}]}], 
 Dividers -> All]

enter image description here

$\endgroup$
2
$\begingroup$
SeedRandom[1234];

rand = {1, 2, 3};
el = EdgeList[CompleteGraph[5]];
g = CompleteGraph[5,
  VertexLabels -> "Name", 
  EdgeLabels -> Table[el[[i]] -> RandomChoice[rand], {i, Length[el]}]]

enter image description here

label[graph_, edges_] := First@Cases[Options[g, EdgeLabels],
   Rule[UndirectedEdge @@ Sort[edges],
     lbl_] :> lbl, Infinity]

label[g, {1, 4}]

(* 1 *)

label[g, {5, 3}]

(* 3 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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