function masks = subsets(n, K)
% SUBSETS Create all subsets of {1,...,n} of size up to K and return as a bit vector
% masks = subsets(K)

masks = bintab(n);
Tsize = zeros(1,2^n); % Tsize(i) = num. non zeros in the binary repr. of i
for i=1:2^n
  Tsize(i) = length(find(masks(i,:)));
end
% Currently the rows of 'masks' are in binary order
% Sort them in order of size
[junk,perm] = sort(Tsize);
masks = masks(perm,:);
m = 0;
for k=0:K
  m = m + choose(n,k);
end
% m = sum_{k=1}^K choose(n,k)
masks = masks(1:m, :);
