Home > OS >  List of vectors, whose sum of elements equal to the loop variable
List of vectors, whose sum of elements equal to the loop variable

Time:05-04

I want to create a list of vectors, where the elements of each vector in the list sums up to the loop variable without considering order of elements and repetition into account. For eg.

k=1, list ={[1]}; 
k=2, list ={[1,1],[2]}; 
k=3, list ={[1,1,1],[1,2],[2,1],[3]}; 
k=4, list ={[1,1,1,1],[1,3],[3,1],[2,2],[2,1,1],[1,2,1],[1,1,2],[4]};

and so on. The length of the list is $2^{k-1}$. Is there any easy strategy to do this in MATLAB?

CodePudding user response:

There is an easy recursive strategy: If you have a list of the integer partitions with the sum of some k-1, it is easy to generate the partitions with sum k: Given some partition, we can either append an 1 to create a new partition, or we can just increment the last entry., so something like this should work.

k = 5;
sumk = {[1]}; % anchor
for current_sum = 2:k    % recursion
    new_sumk = {};
    % (a) create new list by appending an 1
    new_append = cellfun(@(x)[x,1], sumk, 'Un', 0);
    % (b) create new list by increasing last element
    new_increment = cellfun(@(x)[x(1:end-1), x(end) 1], sumk, 'Un', 0)
    sumk = [new_append, new_increment];
end

% print the whole thing:
for l = 1:length(sumk)
    disp(sumk{l})
end
  • Related