function f = cluster_bestwcut(A, k)
% Asymmetric spectral clustering.
%
% A:
%    the asymmetric distance matrix
% k:
%    the number of groups
%
% See also: cluster_spectral

% References:
% Marina Meila and William Pentney, "Clustering by weighted cuts in directed graphs",
%    Proc. of the 2007 SIAM International Conference on Data Mining, 2007.

% Copyright 2012 Levente Hunyadi

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

d = sum(A, 2);  % a column vector containing the sum of rows
D = diag(d);
Disqrt = diag(1./realsqrt(d));
H = 0.5 * Disqrt * (2*D - A - A') * Disqrt;
[Y,Sigma] = eig(H);
sigma = diag(Sigma);

[~,ix] = sort(sigma, 'ascend');
Y = Y(:,ix(1:k));
%X = Disqrt * Y;
X = bsxfun(@rdivide, Y, sqrt(sum(Y.^2,2)));  % normalize the rows of Y to unit length

f = kmeans(X, k);
