Main Content

combnk

(Not recommended) Enumeration of combinations

combnk is not recommended. Use the MATLAB® function nchoosek instead. For more information, see Compatibility Considerations.

Description

example

C = combnk(v,k) returns a matrix containing all possible combinations of the elements of vector v taken k at a time. Matrix C has k columns and n!/((n – k)! k!) rows, where n is the number of observations in v.

Examples

collapse all

Create a character array of every four-letter combination of the characters in the word 'tendril'.

C = combnk('tendril',4);

C is a 35-by-4 character array.

Display the last five combinations in the list.

last5 = C(31:35,:)
last5 = 5x4 char array
    'tedr'
    'tenl'
    'teni'
    'tenr'
    'tend'

List all two-number combinations of the numbers one through four.

C = combnk(1:4,2)
C = 6×2

     3     4
     2     4
     2     3
     1     4
     1     3
     1     2

Because 1:4 is a vector of doubles, C is a matrix of doubles.

Input Arguments

collapse all

Set of all elements, specified as a vector.

Example: [1 2 3 4 5]

Example: 'abcd'

Data Types: single | double | logical | char

Number of elements to select, specified as a nonnegative integer scalar. k can be any numeric type, but must be real.

There are no restrictions on combining inputs of different types for combnk(v,k).

Example: 3

Data Types: single | double

Output Arguments

collapse all

All combinations of v, returned as a matrix of the same type as v. C has k columns and n!/((n – k)! k!) rows, where n is the number of observations in v.

Each row of C contains a combination of k items selected from v. The elements in each row of C are listed in the same order as they appear in v.

If k is larger than n, then C is an empty matrix.

Limitations

combnk is practical only for situations where v has fewer than 15 observations.

Version History

Introduced before R2006a

collapse all

R2020b: combnk is not recommended

combnk is not recommended. Use the MATLAB function nchoosek instead. There are no plans to remove combnk.

To update your code, change instances of the function name combnk to nchoosek. You do not need to change the input arguments. For example, use C = nchoosek(v,k). The output C contains all possible combinations of the elements of vector v taken k at a time. Note that C from nchoosek can have a different order compared to the output from combnk.

The nchoosek function has several advantages over the combnk function.

  • nchoosek also returns the binomial coefficient when the first input argument is a scalar value.

  • nchoosek has extended functionality using MATLAB Coder™.

  • nchoosek is faster than combnk.

See Also

| |