X=randn(3,5);
P=randperm(5);
Y=X(:,P);
Z=X - reshape(Y,[3 1 5]);

% evaluate distances
is = repmat(1:5, factorial(5), 1);
js = perms(1:5);
rr = squeeze(sum(Z.^2,1));
% imin
[~,ibest] = min(rr, [], 2);

dist=sum(rr(sub2ind([5 5], is, js)).^2, 2);
[mind,ip] = min(dist);

disp(js(ip,:));
disp(P(js(ip,:)));
disp(P(ibest));