nsumk
function [x] = nsumk(n,k,option)
% NSUMK listing of positive or non-negative integer n-tuples summing to k
%
%    [X] = NSUMK(N,K) produces a matrix X with
%    nchoosek(K+N-1,N-1) rows and n columns. Each row comprises
%    non-negative integers summing to k. The ordering of rows follows the
%    same convention as NCHOOSEK, which is undocumented but with some
%    reliability appears to be lexicographic. The reverse of this presumed ordering
%    is a natural way to list coefficients of polynomials in N variables of degree K.
%    As per nchoosek, this syntax is only practical for situations where N is
%    less than about 15.
%
%  EXAMPLE:   [x] = nsumk(5,2,...) returns a matrix x in which rows sum to 2

switch option
    case 'nonnegative'
    m = nchoosek(k+n-1,n-1);
    dividers = [zeros(m,1),nchoosek((1:(k+n-1))',n-1),ones(m,1)*(k+n)];
    x = diff(dividers,1,2)-1;

    case 'positive'
    % for positive interger tuples
    c = nchoosek(2:k,n-1);
    n_c = size(c,1);
    c = [ones(n_c,1),c,ones(n_c,1)*(k+1)];
    x = diff(c,1,2);
end

end