MATLAB: All possible combinations such that sum of all numbers is a fixed number

all permsfixed sum

I need to find all possible combinations of numbers 1:8 such that sum of all elements is equal to 8
Eg
1 7
2 2 4
1 3 5
1 2 2 3
1 1 1 1 1 1 1 1
A number can repeat itself. But a combination must not.. i.e 1 2 2 3 and 2 1 2 3 I need the the solution in ascending order So there will be only one possibility of every combination
VEC = [1:8];
NUM = 8;
n = length(VEC);
finans = zeros(2^n-1,NUM);
for i = 1:(2^n - 1)
ndx = dec2bin(i,n) == '1';
if sum(VEC(ndx)) == NUM
l = length(VEC(ndx));
VEC(ndx)
end
end
but they dont include the possibilities where the numbers repeat.

Best Answer

No need to reinvent the wheel. There's several entries on FEX. See John D'errico's partitions for example.