1

A very simple example :

A=[100 250 300]

How do I find all possible combinations as long as each combination has a sum of less than 500 ?

3
  • Is your array always of size 3? Commented Feb 16, 2013 at 22:51
  • To clarify, for the above example you want to return [250 100], [100], [250], [300], [300 100]? Commented Feb 16, 2013 at 22:52
  • @learnvst Yes, exactly. Commented Feb 16, 2013 at 22:54

2 Answers 2

1

This code should work. The result will be stored in the cell array C:

A = [100 250 300];
B = 500;
C = cell(0);

for i = 1:size(A,2)
    D = nchoosek(A,i);
    for j = 1:size(D,1)
        if (sum(D(j,:)) < B)
            C{end+1} = D(j,:);
        end
    end
end

or more compact:

A = [100 250 300];
B = 500;
C = cell(0);

for i = 1:size(A,2)
    C = [C; num2cell(nchoosek(A,i),2)];
end
C = C(cellfun(@(x) sum(x), C) < B);
Sign up to request clarification or add additional context in comments.

Comments

0

This simple code

A=[100 250 300];
p = perms(A);

for nn = 1:numel(A)    
    p(sum(p(:,1:nn), 2) < 500, 1:nn)
end

Gives the following output

ans =

   300
   300
   250
   250
   100
   100

ans =
   300   100
   250   100
   100   250
   100   300

If you want to remove duplicates, like [300 100] and [100 300], simply use the sort command to sort the values and then you can remove duplicates using unique

2 Comments

Can you explain how to remove duplicates ? I can't get it to work.
Look at the documentation for unique, specifically the bit about C = unique(A,'rows')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.