%% Discard Graph Components Based on Size
% Use the second output of conncomp to extract the largest component of a graph or to remove components below a certain size.
%
% Create and plot a directed graph. The graph has one large component, one small component, and several components that contain only a single node.

s = [1 2 2 3 3 3 4 5 5 5 8 8 9];
t = [2 3 4 1 4 5 5 3 6 7 9 10 10];
G = digraph(s,t,[],20);
plot(G,'Layout','layered')

%
% Calculate the weakly connected components and specify two outputs to conncomp to get the size of each component.

[bin,binsize] = conncomp(G,'Type','weak')

%
% Use binsize to extract the largest component from the graph. idx is a logical index indicating whether each node belongs to the largest component. The subgraph function extracts the nodes selected by idx from G.

idx = binsize(bin) == max(binsize);
SG = subgraph(G, idx);
plot(SG)

%
% A similar use of binsizes is to filter out components based on size. The procedure is similar to extracting the largest component, however in this case each node can belong to any component that meets the size requirement.
% Filter out any components in G that have fewer than 3 nodes. idx is a logical index indicating whether each node belongs to a component with 3 or more nodes.

idx = binsize(bin) >= 3;
SG = subgraph(G, idx);
plot(SG)

% Copyright 2012 The MathWorks, Inc.