Code covered by the BSD License  

Highlights from
VChooseKR

Be the first to rate this file! 12 Downloads (last 30 days) File Size: 13.9 KB File ID: #26277
image thumbnail

VChooseKR

by

 

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

| Watch this File

File Information
Description

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.

Acknowledgements

Picking Elements From A Set and Combinator Combinations And Permutations inspired this file.

This file inspired V Choose Ko.

MATLAB release MATLAB 7.8 (R2009a)
Other requirements Precompiled mex: http://www.n-simon.de/mex
Tags for This File   Please login to tag files.
Please login to add a comment or rating.

Contact us