2
$\begingroup$

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:

WeaklyConnectedGraphQ[g]
False

I know there are two components:

Length[WeaklyConnectedComponents[g]]
2

I know how many vertices are in each component:

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

And I know what vertices are in each component:

WeaklyConnectedComponents[g]
{{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?

$\endgroup$

1 Answer 1

5
$\begingroup$

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]] ]
$\endgroup$
3
  • $\begingroup$ That's perfect, and so simple! Thanks! $\endgroup$
    – CurtLH
    Commented Mar 27, 2014 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
    Commented Mar 27, 2014 at 15:21
  • 1
    $\begingroup$ @Curtis you should do WeaklyConnectedComponents[g][[2]] $\endgroup$
    – halmir
    Commented Mar 28, 2014 at 14:06

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.