VChooseKR

Version 1.0.0.0 (13.9 KB) by Jan
Choose K elements from a vector with repetitions and without order [MEX]
1K Downloads
Updated 5 Jan 2010

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.

INPUT:
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.

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

EXAMPLES:
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):
http://www.mathworks.com/matlabcentral/fileexchange/26190
VChooseKRO (repetitions, order):
http://www.mathworks.com/matlabcentral/fileexchange/26242

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

Cite As

Jan (2024). VChooseKR (https://www.mathworks.com/matlabcentral/fileexchange/26277-vchoosekr), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2009a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Elementary Math in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.0.0.0