Hello Mathematica friends!

I've got a network with thousands of edges and vertices, but not all in one connected component. I'm trying to extract specific connected components from the network, and assign them as new variables.

g = Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 1 \[UndirectedEdge] 3, 4 \[UndirectedEdge] 5, 7 \[UndirectedEdge] 6, 8 \[UndirectedEdge] 6, 5 \[UndirectedEdge] 7, 7 \[UndirectedEdge] 8}]

I know it's a disconnected component because of:


I know there are two components:


I know how many vertices are in each component:

Length /@ WeaklyConnectedComponents[g]
{5, 3}

And I know what vertices are in each component:

{{7, 6, 5, 8, 4}, {3, 2, 1}}

What I don't know is how to a assign on of these components to a new variable to then proceed with analysis on just a single connected component?


I understand that you want the subgraph of g that corresponds to the vertices in one of the w.c.c (say, the first one). How about:

Subgraph[g, First@WeaklyConnectedComponents[g]]

If you want, say, the 13th connected component, just do

Subgraph[g, WeaklyConnectedComponents[g][[13]] ]
  • $\begingroup$ That's perfect, and so simple! Thanks! $\endgroup$
    – CurtLH
    Mar 27 '14 at 13:27
  • $\begingroup$ what if I wanted to second or third subgraph? I tried just replacing First@WeaklyConnectedComponents with Second@WeaklyConnectedComponents but that didn't appear to work. $\endgroup$
    – CurtLH
    Mar 27 '14 at 15:21
  • 1
    $\begingroup$ @Curtis you should do WeaklyConnectedComponents[g][[2]] $\endgroup$
    – halmir
    Mar 28 '14 at 14:06

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.