function label= kernel_kmeans(X,K,gamma)
%% Compute the kernel
N = size(X,1);
kernel = exp(-gamma*(repmat(sum(X.*X,2),1,N) + repmat(sum(X.*X,2),1,N)' - 2*X*X'));

%% Initialize the assignment matrix
Z = repmat([1,zeros(1, K-1)],N,1);  %Z为N*K
[~,pos] = sort(sum(X.^2,2));%sorted是排序后的序列,pos是sorted中各数原来的索引
for k = 1:K-1
    Z(pos(k),:) = 0;
    Z(pos(k),k+1) = 1;
end
%% Run Kernel K-means
converged = 0;
dist = zeros(N,K);
label = ones(N,1);    %随机分配标签  N*1
while ~converged
    Nk = sum(Z,1);%Z的每一列之和
    for k = 1:K
        % Compute kernelised distance
        dist(:,k) = diag(kernel) - (2/(Nk(k)))*sum(repmat(Z(:,k)',N,1).*kernel,2) + ...
            Nk(k)^(-2)*sum(sum((Z(:,k)*Z(:,k)').*kernel));
    end
    oldZ = Z;
    Z = (dist == repmat(min(dist,[],2),1,K));
    Z = 1.0*Z;
    if sum(sum(oldZ~=Z))==0
        converged = 1;
    end
    
    %%
    for k = 1:K
        label(Z(:,k)==1)=k;
    end
end