How do you filter the results of the nchoosek(v,k) command?
3 views (last 30 days)
Show older comments
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
Answers (2)
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
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.
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.
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!