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 ?
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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.