. nmultichoosek.
v = 1 : 8;
combs = cell(length(v),0);
for i = v
combs{i} = nmultichoosek(v,i);
end
, combs , . , i-th combs{4} .
. , cellfun
sums = cellfun(@(x)sum(x,2),combs,'UniformOutput',false);
sums .
sums{4} combs{4}.
- .
fixed_sum = 10;
indices = cellfun(@(x)x==fixed_sum,sums,'UniformOutput',false);
indices , , . , indices{4}(1) , 4 fixed_sum.
, , .
valid_combs = cell(length(v),0);
for i = v
idx = indices{i};
c = combs{i};
valid_combs{i} = sortrows(c(idx,:));
end
valid_combs- this is a cell similar to combs, but only with combinations that are summed to the desired value and sorted by the number of numbers used: it valid_combs{1}has all valid combinations with 1 number, valid_combs{2}with two numbers, etc. In addition, thanks sortrows, combinations with the same number of numbers are also sorted. For example, if fixed_sum = 10, that valid_combs{8}is,
1 1 1 1 1 1 1 3
1 1 1 1 1 1 2 2
This code is pretty efficient, on my oldest laptop I can run it in 0.016947 seconds.