function Cluster=Cluster_coef(M,thr)
%function Cl=Cluser_coef(M) calculates the clusetering coefficient of a graph.
% M(n,n) - adj matrix of a graph.

% ============= Input data validation ==================
if nargin<1,
  error('There are no input data!')
end
sz=size(M);
if sz(1) ~= sz(2),
    error('Matrix should be square!')
end
n=sz(1);% n - размерность матрицы (dimmension of the matrix)
% =============   Calculations        ==================
Cl=0;           % Количество циклов длиной 3(Number of cycles with length 3)
num=0;          % Количество путей длиной 2 (number of triples)
for node1=1:n   %  node1 - number of 1-st node in a cycle
    for node2=1:n %  node2 - number of 2-nd node in a cycle
        if ((node1~=node2)&&(M(node1,node2)<thr))% if node1 and node2 are connected - 
            node3=1;%  node3 - number of 3-rd node in a cycle. Trying to search it
              while (node3<n),
                  if (node1~=node3)&&(node2~=node3)&&(M(node2,node3)<thr)%if 2nd & 3-rd node is connected
                      num=num+1; % We found one more tripple
                     if ((M(node3,node1)<thr)) %If thease nodes connected in cycle - 
                        Cl=Cl+1;%We found one more cycle
                      end
                  end
                  node3=node3+1;
              end
          end
  end
end
if num~=0
Cluster=Cl/num;
else
    Cluster=0;
end