How do you filter the results of the nchoosek(v,k) command?

3 views (last 30 days)
I used the nchoosek(v,k) command to find out all the 7 number combinations possible using 12 distinct numbers (where v=[5 7 13 14 17 18 21 24 27 35 37 39] and k=7). The result was a 7 X 792 matrix. Is there a way to filter the results in a way where it omits all the combinations which contain consecutive numbers?
Thank you.
  3 Comments
Moataz
Moataz on 27 Mar 2018
Firstly, thank you for your help. By consecutive numbers I mean, 13,14. I probably could have used a better example. For clarity's sake let v = [5 6 7 8 15 19 24 25 26 31 38 45] where the consecutive numbers are 5,6,7,8 and 24,25,26. I would like to to be able to find all the 7 number combinations using those 12 numbers where there are no consecutive numbers.

Sign in to comment.

Answers (2)

Birdman
Birdman on 27 Mar 2018
Edited: Birdman on 27 Mar 2018
Something like this?
A=nchoosek(v,k);
A(any([diff(A.')==1].',2),:)=[]
  10 Comments
Jan
Jan on 27 Mar 2018
You are an expert in Simulink and with symbolic calculations - two fields I do not have any experiences in.
:-) It is time to stop the flatter. We do not want others to get jealous.

Sign in to comment.


Jan
Jan on 27 Mar 2018
Creating all combinations and removing the unwanted ones can be very expensive. The number of combinations grows rapidly with the size of the input. Therefore a constructive method might be more efficient, when your RAM explodes.
v = [5 7 13 14 17 18 21 24 27 35 37 39]
k = 7;
% Use the first value if the dist
index = ([false, diff(v) == 1]);
v1 = v(index);
w = v(~index);
% All combinations of the shortened vector:
comb = nchoosek(w, k);
% Create the full set by inflating:
for i1 = v1
match = any(comb == i1 - 1, 2);
combx = comb(match, :);
combx(combx == i1 - 1) = i1;
comb = cat(1, comb, combx);
end
This replies the same vectors as Birdman's solution, but in a different order. Maybe you want to apply sortrows afterwards.
If nchoosek(v,k) is too huge for your RAM and many rows are removed, this might be working.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!