Just use nchoosek and double for -loop to go through all possible combinations of elements in B :
SA = sum(A); for k = 1:numel(B) for idx = nchoosek(1:numel(B), k)' B_subset = B(idx); if (SA + sum(B_subset) <= 2000) disp([A(:)', B_subset(:)']) end end end
This displays all combinations with an amount less than (or equal to) 2000. For your example, we get:
10 40 90 130 200 260 320 100 10 40 90 130 200 260 320 300 10 40 90 130 200 260 320 500 10 40 90 130 200 260 320 100 300 10 40 90 130 200 260 320 100 500 10 40 90 130 200 260 320 300 500 10 40 90 130 200 260 320 100 300 500
Explanation:
Internal for -loop :
The inner for -loop uses nchoosek(1:numel(B), k) , which generates all k-length combinations from 1 ... length (B) (I use numel instead of length out of habit, in which case it has the same effect ) For example, in our case B has 4 elements, so for k = 3 we get nchoosek(1:4, 3) :
1 2 3 1 2 4 1 3 4 2 3 4
From this we get all possible combinations of k-length indices of elements from B At each iteration, this for -loop assigns a different idx index combination. How do we convert indices B to real elements? We just write B(idx) .
The combination is checked inside the loop: if the total sum(A) + sum(B(idx)) less (or equal to 2000), this combination is displayed.
External for -loop :
The external for -loop simply iterates over all possible combination lengths (i.e., over all possible k values).
Hope this helps!
PS:
Some MATLAB programming tips for the future:
1. Variable names are case-sensitive.
2. You do not need to increase the loop variable. The for loop does this automatically for you.
source share