function [fit,vaf,lengths] = centfit(prox)

% CENTFIT finds the least-squares fitted centroid metric (FIT) to
% PROX, the input proximity matrix (with a zero main diagonal
% and a dissimilarity interpretation);
% The $n$ values that serve to define the approximating sums,
% $g_{i} + g_{j}$, are given in  the vector LENGTHS of size $n \times 1$.

n = size(prox,1);
lengths = zeros(n);
rsums = sum(prox);
tsum = sum(rsums);

lengths = (rsums/(n-2)) - (tsum/(2*(n-1)*(n-2)));

for i = 1:n
   for j = 1:n
      
      if (i ~= j)
         
         fit(i,j) = lengths(i) + lengths(j);
         
      else
         
         fit(i,j) = 0;
      end
   end
end

   
  aveprox = sum(sum(prox))/(n*(n-1));

for i = 1:n
   for j = 1:n
      if( i ~= j)
         proxave(i,j) = aveprox;
      else
         proxave(i,j) = 0;
      end
   end
end

diff = sum(sum((prox - fit).^2));

denom = sum(sum((prox - proxave).^2));

vaf = 1 - (diff/denom);
      

