1

How to generate all possible combinations of K instances of N objects in Matlab?

For example, if we have N=3 objects A, B and C, and wish to generate combinations of K=2 instances, we should get

AA
AB
AC
BA
BB
BC
CA
CB
CC

I.e. this is how figures in a number combinate.

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

2 Answers2

3

You can use fullfact:

fullfact([3 3])

This will produce all the combinations of 3 elements in the first row and 3 elements in the second row, resulting with:

 1     1
 2     1
 3     1
 1     2
 2     2
 3     2
 1     3
 2     3
 3     3
Mercury
  • 1,886
  • 5
  • 25
  • 44
1

Using allcomb from matlab file exchange:

allcomb(['A','B','C'],['A','B','C'])

download

A more generalized method:

s='A':'D'
k=3
e=repmat({s},1,k)
allcomb(e{:})
Daniel
  • 36,610
  • 3
  • 36
  • 69