Main Content

nchoosek

Binomial coefficient or all combinations

Description

b = nchoosek(n,k) returns the binomial coefficient for the number of combinations of n items taken k at a time. The binomial coefficient is defined as

Cnk=(nk)=n!(nk)!k!.

n and k must be nonnegative integers.

example

C = nchoosek(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 m!/((mk)! k!) rows, where m is length(v).

example

Examples

collapse all

b = nchoosek(5,4)
b = 
5
v = 2:2:10;
C = nchoosek(v,4)
C = 5×4

     2     4     6     8
     2     4     6    10
     2     4     8    10
     2     6     8    10
     4     6     8    10

v = uint16([10 20 30]);
C = nchoosek(v,uint16(2))
C = 3x2 uint16 matrix

   10   20
   10   30
   20   30

Input Arguments

collapse all

Number of possible choices, specified as a nonnegative integer scalar. n can be any numeric type, but must be real.

Example: 10

Example: int16(10)

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Number of selected choices, specified as a nonnegative integer scalar. k can be any numeric type, but must be real. nchoosek(n,k) requires that n and k be the same type or that at least one of them be of type double.

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

Example: 3

Example: int16(3)

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Set of all choices, specified as a vector.

Example: [1 2 3 4 5]

Example: [1+1i 2+1i 3+1i 4+1i]

Example: int16([1 2 3 4 5])

Example: [true false true false]

Example: ['abcd']

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char
Complex Number Support: Yes

Output Arguments

collapse all

Binomial coefficient, returned as a nonnegative scalar value. b is the same type as n and k. If n and k are of different types, then b is returned as the nondouble type.

All combinations of v, returned as a matrix of the same type as v. Matrix C has k columns and n!/((nk)! k!) rows, where n is length(v).

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

If k > numel(v), then C is an empty matrix.

Limitations

  • When b = nchoosek(n,k) is sufficiently large, nchoosek displays a warning that the result might not be exact. In this case, the result is only accurate to 15 digits for double-precision inputs, or 8 digits for single-precision inputs.

  • C = nchoosek(v,k) is only practical for situations where length(v) is less than about 15.

Extended Capabilities

Version History

Introduced before R2006a