function f = cluster_spectral(S, k)
% Symmetric spectral clustering.
%
% S:
%    the scatter matrix
% k:
%    the number of groups
%
% See also: cluster_bestwcut

% Copyright 2012 Levente Hunyadi

narginchk(2,2);
validateattributes(S, {'numeric'}, {'nonempty','real','2d','>=',0,'<=',1});
validateattributes(k, {'numeric'}, {'positive','integer','scalar'});

Disqrt = diag(1./realsqrt(sum(S, 1)));  % diagonalization of inverted square root
S = Disqrt * S * Disqrt;
[U,Sigma] = eig(S);
sigma = diag(Sigma);

[~,ix] = sort(sigma, 'descend');  % due to formulation, largest eigenvalues are of interest
U = U(:,ix(1:k));  % dimensionality reduction to number of clusters
sigma = sigma(ix(1:k));

f = kmeans(U * diag(1./realsqrt(sigma)), k);
