
function final = smoothLinks(mat,K);

%
% Starts from a binary link matrix and finds a version that
% has all path-distances up to K. If, for example, K=3 then
% the matrix will have element 1 when there is direct connection,
% 2 when another node can be reached through 2 links, and 3
% if it can be reached through 3 links.
%
% Leaves ones on the diagonal, and zero means there is no link
%
% Use only for relatively small values of K, perhaps roughly 2-5.
%

N=size(mat,1);

% Make the matrix symmetric
mat_sym = double(or(mat,mat'));

% Ensure ones at diagonal
for i=1:N;
  mat_sym(i,i)=1;
end;

final = mat_sym;
final_binary = final;

for k=2:K;
  twostep = mat_sym^k;
  twostep(find(twostep>1)) = 1;
  twostep = twostep-final_binary;
  
  final = final + k*twostep;
  final_binary = final_binary + twostep;
end;
