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

integerlistsumvectors

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.

•    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]);   end