Code covered by the BSD License  

Highlights from
KTHCOMBN

5.0

5.0 | 1 rating Rate this file 6 Downloads (last 30 days) File Size: 2.33 KB File ID: #33922

KTHCOMBN

by Jos (10584)

 

24 Nov 2011 (Updated 17 Jan 2012)

K-th combination(s) of elements

| Watch this File

File Information
Description

KTHCOMBN - the K-th combination of elements

M = KTHCOMBN(V,N,K) returns the K-th combination(s) of N elements of the elements in vector V. N is a positive scalar, and K is a vector of one or more integers between 1 and numel(V)^N.
V can be a vector of numbers, characters, cells strings, or even structures.
 
[M,IDX] = KTHCOMBN(V,N,K) also returns an index matrix, so that M = V(IDX).
 
Examples:
      V = [7 31] , N = 3 , K = [7 4]
      M = kthcombn(V, N, K)
      % returns the 2-by-3 matrix:
      % -> 31 31 7
      % 7 31 31
      % being the 7th and 4th combination (out of 9) of 3 elements of the V.
 
      kthcombn('abcde',10, 5^9)
      % -> aeeeeeeeee
      
      V = cellstr(['a':'z'].') ; N = 5 ; K = [1 10000000 11881376] ;
      M = kthcombn(V,N,K)
      % returns the first, 10 millionth, and the last combination
      % -> 'a' 'a' 'a' 'a' 'a'
      % 'v' 'w' 'y' 'x' 'j'
      % 'z' 'z' 'z' 'z' 'z'
 
All elements in V are regarded as unique, so M = KTHCOMBN([2 2],3, K) returns [2 2] for all values of K.
 
This function does the same as
      M = COMBN(V,N)
      M = M(K,:)
but it does not need to create all combinations first, before selecting, thereby avoiding some obvious memory issues with large values of N.
Beware of round-off errors for large values of N and K (see INTMAX).
For V = [0 1], KTHCOMBN returns a similar results as dec2bin(K-1,N)-'0'
 
See also nchoosek, perms
and combn, allcomb, nchoose on the File Exchange

MATLAB release MATLAB 7.12 (2011a)
Other requirements should work on most releases
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (1)
15 Jan 2012 Manu

love it! I have been using combn a lot but this time I really needed something which can give me the kth combination without storing the whole big matrix. This is perfect.

Please login to add a comment or rating.
Updates
17 Jan 2012

check K > 0 instead of K >= 0; fixed some spelling in the help

Tag Activity for this File
Tag Applied By Date/Time
combinations Jos (10584) 28 Nov 2011 09:38:25
permutations Jos (10584) 28 Nov 2011 09:38:25
selection Jos (10584) 28 Nov 2011 09:38:25
matrix Jos (10584) 28 Nov 2011 09:38:25
statistics Jos (10584) 28 Nov 2011 09:38:25
combn Manu 15 Jan 2012 02:36:47

Contact us at files@mathworks.com