function 	[TTT,err]=permmatch(fi,se,K); 

%Permutes columns of the first matrix to match the second matrix, giving the least error (city distance) and
%among ties: the biggest number of zeros (coincidences)
% The first matrix is binarized
%Returns the error (err) and the permuted matrix (TTT)

fib=double(fi>0.5);

P = perms(1:K);

err=10000000; 
nz=-1;

for i=1:factorial(K)

pfib=fib(:,P(i,:));

ea=sum(sum(abs(pfib-se)));

if ea <err

err=ea;
nz=sum(sum(abs(pfib-se))==0);
pf=i;

elseif ea==err
    nza=sum(sum(abs(pfib-se))==0);
    if nza< nz
        pf=i;
        nz=nza;
    end
end


end

TTT=fi(:,P(pf,:));

 