function clustersize=componentsize(adj)
% COMPONENTSIZE Calculate the sizes of the connected components of a
% network.
%
% S = COMPONENTSIZE(A) returns the sizes from largest to smallest. The
% number of components is then LENGTH(S).
%
% A must be square and if it is not symmetric COMPONENTSIZE will calculate
% the sizes of the weak components.
% Version 1.0 Ben Skellett 01/10/03
if size(adj,1)~=size(adj,2)
error('Matrix is not square');
end
if nnz(adj-adj')~=0
disp('Adjacency matrix is not symmetric.')
disp('Will calculate size of weak components.')
adj=adj+adj';
end
adj=full(adj); %in case of sparse adj
N=length(adj);
count=1; %initialize count
checked=[]; %initialize list of checked vertices to null
unchecked=1:N; %initialize unchecked vertices to all
indegreethreshold=0; %1 catches all clusters that are not single nodes, 0 catched all
while length(unchecked) > 0
linked=unique([unchecked(1); find(adj(:,unchecked(1)))]); %find vertices connected to first vertex in 'unchecked' list
clustersize(count)=1;
while length(linked) > clustersize(count) %while size of cluster increases
clustersize(count)=length(linked); %record cluster size
[i,j]=find(adj(:,linked));
linked=unique([i; linked]); %find vertices that link to others already in cluster
end
checked=unique([checked; linked]); %update checked
unchecked=setdiff((1:N),checked); %update unchecked
count=count+1;
end
clustersize=sort(clustersize); %sort output
clustersize=clustersize(end:-1:1);