function [W, obj] = NonnegativeSpectralClustering(A, r, max_iter, check_step, W0)
% Nonnegative Spectral Clustering (NSC)
% He Zhang, Sep. 2012
% Ref: C. Ding et al.: Nonnegative matrix factorization for combinato rial optimization: 
% Spectral clustering, graph matching, and clique finding, ICDM, IEEE, 2008

n = size(A,1);
rand('seed', 0);
if ~exist('W0', 'var') || isempty(W0)
    W0 = rand(n,r);
end
W = W0;
for iter=1:max_iter
    AW = A*W;
    W = W .* sqrt(AW./(bsxfun(@times, sum(A,2), W*(W'*AW))+eps));
    if mod(iter, check_step)==0
        obj = -trace(W'*A*W);
        fprintf('NonnegativeSpectralClutering: iter=%d, obj=%6.5f\n', iter, obj);
    end
    
end

if nargout>1
    obj = -trace(W'*A*W);
end
