find all combination for n elements in matlab

You can use the combnk function to find all combinations of n elements. It takes two arguments: the set of elements and the number of elements to choose in each combination. Here's an example:

main.m
elements = [1, 2, 3, 4];
num_elements = 2;

combinations = combnk(elements, num_elements);
91 chars
5 lines

The above code will compute all combinations of two elements from the set 1:4.

The resulting combinations matrix will be an nCr x num_elements matrix where nCr is the number of combinations of n elements taken r at a time (i.e., n!/((n-r)!r!)).

For the example above, the combinations matrix will be:

main.m
1   2
1   3
1   4
2   3
2   4
3   4
36 chars
7 lines

Each row represents a unique combination of two elements from the set 1:4.

related categories

gistlibby LogSnag