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

4 views (last 30 days)
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.
  2 Comments
Jan
Jan on 16 Apr 2015
While a simple brute force approach solves this for small numbers easuily, for large numbers even stroing the results is not trivial due to the huge number of results. So please specify for which range of values you want the function to work.

Sign in to comment.

Accepted Answer

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

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!