function x = simplex(y)
% Project onto simplex x>=0, sum(x)==1 using Chen & Ye, Projection Onto a
% Simplex, arXiv:1101.6081v2

%   Copyright 2017 The MathWorks, Inc.

n = numel(y);

ys = sort(y,'descend');

t = (cumsum(ys) - 1) ./ (1:n)';

idx = find(t>=ys,1,'first');

if isempty(idx)
    that = mean(y) - 1/n;    
else
    that = t(idx);
end

x = y - that;
x(x<0) = 0;

if any(x>0)
    x = x/sum(x);
end

end
