MATLAB: What is the fastest way to list all positive integer vectors whose sum of elements equals K.


For example I want to list all row vectors (1,5) whose elements are positive integers and sum of elements equals to 20. I am looking for a fast way which not use the loop-for for each elements. Please help.

Best Answer

  • K = 20; % The required sum
    n = 5; % The number of elements in the rows
    c = nchoosek(2:K,n-1);
    m = size(c,1);
    A = zeros(m,n);
    for ix = 1:m
    A(ix,:) = diff([1,c(ix,:),K+1]);
    The rows of A will have the vectors you seek. In your example there will be 19!/4!/15! = 3876 such row vectors.
    Note: I don't think this code works for the trivial case of n = 1.