File Exchange

image thumbnail


version 1.0 (13.9 KB) by

Choose K elements from a vector with repetitions and without order [MEX]



View License

VChooseKR(V, K) creates a matrix, which rows are all combinations created by choosing K elements of the vector V without order and with repetitions.

V: Array of class DOUBLE, SINGLE, (U)INT8/16/32/64, LOGICAL, CHAR.
Prefer (U)INT8 or (U)INT16 for speed.
K: Number of elements to choose.

Y: Matrix of size [(N+K-1 over K), K] and same class as V.

Choose 2 elements from [1,2,3,4]:
VChooseKR(1:4, 2)
==> [1,1; 1,2; 1,3; 1,4; 2,2; 2,3; 2,4; 3,3; 3,4; 4,4]
For speed cast the input to integer types if possible:
Y = VChooseKR(int8(1:64), 3)
is 6 times faster than with DOUBLEs!
To get the combinations of cell arrays, use the combinations of the index:
C = {'a', 'b', 'c', 'd'};
C2 = C(VChooseKR(1:4, 2))
==> C2 = {'a','a'; 'a','b'; 'a','c'; 'a','d'; 'b','b'; 'b','c'; ...
'b','d'; 'c','c'; 'c','d'; 'd','d'}

This MEX version is faster than COMBINATOR of Matt Fig: E.g. ~7 times for K=64, N=2, ~140 times for K=2, N=128. The older PICK of Stefan Stoll is slower than COMBINATOR. See screen shot.

Tested: Matlab 6.5, 7.7, 7.8, WinXP, Compilers: BCC5.5, LCC2.4/3.8, Open Watcom 1.8
Please run the unit-test TestVChooseKR after compiling or to compare the speed with other functions from the FEX, if they are found in the path.

See also: VChooseK (no repetitions, no order):
VChooseKRO (repetitions, order):

I'd appreciate suggestions for improvements and bug reports sent through email - thanks.

Comments and Ratings (0)

MATLAB Release
MATLAB 7.8 (R2009a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video