All possible combinations such that sum of all numbers is a fixed number
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
VRUSHALI PRASADE
le 16 Avr 2015
Commenté : VRUSHALI PRASADE
le 16 Avr 2015
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
I tried a few codes online suggested on http://stackoverflow.com/questions/14848731/find-vector-elements-that-sum-up-to-specific-number-in-matlab
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 commentaires
Jan
le 16 Avr 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.
Réponse acceptée
Guillaume
le 16 Avr 2015
No need to reinvent the wheel. There's several entries on FEX. See John D'errico's partitions for example.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!