4
$\begingroup$

There is a function in Mathematica called CompleteGraph which takes a number and makes a complete graph with that number of vertices:

CompleteGraph[5]

enter image description here

However, in the above the vertices become labelled {1,2,3,4,5}. In contrast, given a set of vertices like e.g.,

vertices={1,3,5,6,8};

I would like to get a complete graph in which the vertices are labelled by the above labels. Is it possible to do that quickly (computationally efficiently) in Mathematica?

$\endgroup$

4 Answers 4

3
$\begingroup$
RelationGraph[UnsameQ, vertices, VertexLabels -> "Name"]    

enter image description here

Alternatively, you can use any of the following to get the same result:

Graph[UndirectedEdge @@@ Subsets[vertices, {2}], VertexLabels -> "Name"]
AdjacencyGraph[vertices, ConstantArray[1, {5,5}]-IdentityMatrix[5], VertexLabels -> "Name"]
SetProperty[VertexReplace[#, Thread[VertexList@# -> vertices]] &@ CompleteGraph[5],
  VertexLabels -> "Name"]

To change just the labels you can use:

CompleteGraph[5, VertexLabels -> {k_ :> vertices[[k]]}]

same picture

$\endgroup$
2
  • $\begingroup$ The first CompleteGraph approach seems to only change the labels but not the vertex names. The other two versions work great, thank you! (True, I guess my question was asking about labels, sorry for the confusion.) $\endgroup$
    – Kagaratsch
    Commented Jan 19, 2019 at 14:23
  • $\begingroup$ @Kagaratsch, my pleasure. Thank you for the accept. $\endgroup$
    – kglr
    Commented Jan 19, 2019 at 14:26
3
$\begingroup$

Using AdjacencyGraph:

AdjacencyGraph[vertices, 
 AdjacencyMatrix[CompleteGraph[Length[vertices]]]]
$\endgroup$
2
$\begingroup$

Another way is with AdjacencyGraph.

SimpleGraph[
 AdjacencyGraph[vertices, ConstantArray[1, Length[vertices] {1, 1}]],
 VertexLabels -> Automatic
]

enter image description here

With IGraph/M, you can zero out the matrix diagonal directly:

AdjacencyGraph[vertices, 
 IGZeroDiagonal@ConstantArray[1, Length[vertices] {1, 1}], 
 VertexLabels -> Automatic]
$\endgroup$
1
$\begingroup$

To me it seems the most direct method is to use VertexReplace, and it doesn't seem any slower than the other methods.

completeGraph[vertexList_List,opts___] := With[
    {g = CompleteGraph[ Length @ vertexList, opts]},
    VertexReplace[g, Thread[VertexList[g] -> vertexList]]
]

So you can do

completeGraph[{a, b, c, d, e, f, g, h}, VertexLabels -> "Name"]

enter image description here

$\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.