function [K] = dist2Kernel(D2)
% Squared distance matrix to kernel.
% 
% Input:
%   D2 -- squared distances
% Output: 
%   K -- kernel matrix
%
% (c) 2008-2016 Zalan Bodo

N = size(D2, 1);

J = eye(N) - (1/N)*ones(N, N); % Centering matrix

K = -0.5 * J * D2 * J;

% Making it positive semi-definite:
[U, S, V] = svd(K);
S(find(S < 0)) = 0;
K = U * S * V';
