Code covered by the BSD License  

Highlights from
COMBNSUB

5.0

5.0 | 1 rating Rate this file 14 Downloads (last 30 days) File Size: 2.26 KB File ID: #41206

COMBNSUB

by

 

09 Apr 2013 (Updated )

Subset of all possible combinations of a fixed number of elements of a vector (v1.1, june 2013)

| Watch this File

File Information
Description

COMBNSUB - subset of all combinations of elements M = COMBNSUB(V,N,IX) returns a subset of all combinations of N elements of the elements in vector V. M has the size numel(IX)-by-N.
 
The output is the same as the sequence M=COMBN(V,N), M=M(IX,:) but this function avoids generating all possible combinations first. The total number of possible combinations increases exponentially (=numel(V)^N). COMBNSUB is particulary useful when you only need one or a small subset of these combinations at a given time.

Example:
      V = 1:5, N = 3, IX = [2 124 21 99]
      M = combnsub(V, N, IX) % returns the 4-by-3 matrix:
      % 1 1 2
      % 5 5 4
      % 1 5 1
      % 4 5 4
      % which are the IXth combinations
      % Check with COMBN
      M2 = combn(V,N) ; isequal(M2(IX,:),M)
      % M2 is a 125-by-3 matrix
 
[M,I] = COMBN(V,N,IX) also returns the index matrix I so that M = V(I).
 
V can be an array of numbers, cells or strings. All elements in V are regarded as unique. Values of IX that exceed the total number of possible combinations (numel(V)^N) are saturated to that value.
 
For empty vectors V, or for N = 0, an empty matrix will be returned.
 
See also perms, nchoosek
and COMBN, ALLCOMBN, PERMPOS, PERMPOSNEXT on the File Exchange

Acknowledgements

Combn (4.3) inspired this file.

MATLAB release MATLAB 7.14 (R2012a)
Other requirements Should work in most ML releases
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (1)
22 Jun 2013 Jan Simon

This is an excellent implementation of a very efficient method. Together with the exhaustive documentation this submission is useful, usable and valuable for the productive work and education. Thanks, Jos!

A tiny simplification: You do not need B(:)', because B is a row vector already.

Updates
24 Jun 2013

1.1 - implemented suggestion of Jan; output is now always a row vector

Contact us