function d = rankdistance(xall)

N = 6834;
M = size(xall,2);
for j = 1:M-1
  tmp = 0;
  for i = 1:N
    for k = 1:N
      if (((xall(i,j+1) < xall(k,j+1)) & (xall(i,M) > xall(k,M)))|((xall(i,j+1) > xall(k,j+1)) & (xall(i,M) < xall(k,M))))
      tmp = tmp+1;
      end;
    end;
  end;
  d(j)=tmp;
  disp(j);
end;

%d(M)=0;
d = d./(N*N);
%d = d + ones(1,M)*(10e-9);  
d = d + ones(1,M-1)*(10e-9);

%semilogy(d2,'rs-');
%semilogy(d3,'rs-');
