function [L,C]=latticestats(G);
%LATTICESTATS.m--statistics a randomized ring lattice (reworklattice.m)
%
%[L,C]=latticestats(G)
%
%Computes the characteristic path length L and the clustering coefficient C
%for the lattice G.  L is the shortest path between vertices averaged over 
%all combinations, and C is the number of edges among each vertex and its
%kv immediate neighbors divided by the max possible (kv*(kv-1)/2).
%G has n vertices and edges defined by n-by-n sparse matrix G.  
%

[m,n]=size(G);
if(m~=n)
	error('G should be square')
end

m=(n*n-n)*0.5; %number entries above main diagonal
L=zeros(m,1);  %storage for stats
C=L;
p=1;
st=1;

for j=1:n-1
   len=breadthfirst(G,j);  %Get distance between j and all nodes
   m=n-j;						%only want lengths to nodes j+1:n
   ind=st-1+(1:m);			%Index into L
   L(ind)=len(j+1:n);		%Store lengths
   
   %Now get cluster stats
   J=find(G(j,:)); %edges (j,J)
   I=find(G(:,j)); %edges (I,j)
   K=[I(:);J(:)];	 		%all vertices to which j is connected
   Cmax=length(K);
   Cmax=Cmax*(Cmax-1)*0.5;%max possible
   if(Cmax==0)
   	plotlattice(G);
      disp(K');
      error(['Cmax=0 for vertex ',int2str(j)]);
   end
   [I,J]=find(G(K,:));  %Find all edges involving vertices in K
   %now, count elements in J that are also in K
  	I=ismember(J,K);
   C(j)=(length(K)+sum(I))/Cmax;
   st=ind(m)+1;      %Increment start
end
L=mean(L); %mean length
C=mean(C);


%%%%%%%%%%%%%%%%%%    BFS     %%%%%%%%%%%%%%%%%%%
function [L]=breadthfirst(G,j);
%BREADTHFIRST.m breadth-first search of graph G (sparse, UT) from vertex j
%
%Standard graph algorithm.  I got it from Cormen Leiserson & Rivest's "Algorithms"

[m,n]=size(G);
color=zeros(n,1);   %white=0, grey=1, black=2
L=zeros(n,1);	 %lengths
pred=zeros(n,1);	 %predecessor verts.

color(j)=1; %gray
L(j)=0;

Q=j;
while(~isempty(Q));
	u=Q(1);
   I=find(G(u,:));
   if(~isempty(I));
   	J=find(color(I)==0);
      if(~isempty(J));
   		J=I(J);
   		color(J)=1;
   		L(J)=L(u)+1;
   		pred(J)=u;
   		Q=[Q,J];
      end
   end
   Q(1)=[];
   color(u)=2;
end
