File Exchange

## ONECOMB

version 1.0.0.0 (2.1 KB) by Darren Rowland

### Darren Rowland (view profile)

Obtain a single combination of N numbers taken K at a time.

Updated 22 Feb 2009

comb = ONECOMB(N,K,M) returns the M-th combination of the sorted list of all combinations from NCHOOSEK.
Makes use of a fast algorithm for the generation of a single combination.

NCHOOSEK(1:4,3) =
[ 1 2 3
1 2 4
1 3 4
2 3 4 ]

onecomb(4,3,3) =
[ 1 3 4 ]

### Cite As

Darren Rowland (2020). ONECOMB (https://www.mathworks.com/matlabcentral/fileexchange/23064-onecomb), MATLAB Central File Exchange. Retrieved .

Alphan Sahin

### Alphan Sahin (view profile)

An update for the reverse function:

N = 50;
K = 6;
M = 498
m = onecomb(N,K,M);

% Reverse
m = fliplr(m)
Mreverse = nchoosek(N,K);
for i = 1:K
if N-m(i)>=i
Mreverse = Mreverse - nchoosek(N-m(i),i);
end
end
Mreverse

Alphan Sahin

### Alphan Sahin (view profile)

Very useful. M can be obtained from the combination as follows:

clear all
close all
clc

N = 50;
K = 6;
M = 498
m = onecomb(N,K,M)

% Reverse
m = fliplr(m);
Mreverse = nchoosek(N,K);
for i = 1:K
Mreverse = Mreverse - nchoosek(N-m(i),i);
end
Mreverse

Alexey

### Alexey (view profile)

Very useful!

What's about reverse function converting conbination to its index?

Husam Aldahiyat

### Husam Aldahiyat (view profile)

Very useful submission, well written.

Rob Campbell

### Rob Campbell (view profile)

This well coded and does what it says. Can be substantially faster than nchoosek. For example:

>> tic, for i=1:1E4;onecomb(10,5,5);end,toc/1E4
ans =
7.3127e-05
>> tic, for i=1:1E4;NCHOOSEK(1:10,5);end,toc/1E4
ans =
3.7945e-04

The 1 star review seems to have missed the point.

Darren Rowland

### Darren Rowland (view profile)

@ Marco/PXlab

It is exactly correct that this function with call structure

C1 = onecomb(N,K,M)

returns the same result as

AC = nchoosek(N,K);
C2 = AC(M,:)

The advantage of this function is that the intermediate array AC is not computed by ONECOMB. The array AC can be immensely large for large N and K approx N/2, and is a waste to compute if one only requires a small number of combinations from the total.

Additionally, if one requires many combinations, my testing (not included here but simple to duplicate) showed that the time to compute all the combinations using NCHOOSEK was approximately the same as computing all the combinations one-at-a-time using ONECOMB.

##### MATLAB Release Compatibility
Created with R14
Compatible with any release
##### Platform Compatibility
Windows macOS Linux