function [subgrad,fobj] = BottomK(X,b)
% Given a vector X(:), This function computes the objective and subgradient of the bottom b function:
% (||X||_1 - ||X||_{topk})
% where b = n*r - k

[m,n] = size(X);
[fobj,subgrad] = BottomK_vec(X(:),b);
subgrad = reshape(subgrad,m,n);
 

function [fobj,subgrad] = BottomK_vec(x,b)
n = length(x);
[abs_x_sort,index] = sort(abs(x),'ascend');
I = index(1:b);
subgrad = zeros(n,1);
subgrad(I) = sign(x(I));
fobj = sum(abs_x_sort([1:b]));
