Amira Akra
Amira Akra

Reputation: 163

generate Combinations from a value in matlab

How to generate the different combinations possible for a certain number Example:

m=2 gives:

[1 1;1 2;2 1;2 2]

m=3 gives: [1 1;1 2;1 3;2 1;2 2;2 3;3 1;3 2;3 3] and so on...

using perms([1 2]) generates [1 2;2 1] only

Upvotes: 0

Views: 108

Answers (2)

Benoit_11
Benoit_11

Reputation: 13945

You can use ndgrid:

m = 3;

[A,B] = ndgrid(1:m);

Here A and B look like this:

A =

     1     1     1
     2     2     2
     3     3     3


B =

     1     2     3
     1     2     3
     1     2     3

So you can concatenate them vertically to get the combinations. Using the colon operator transforms the matrices into column-vectors, i.e. listing all the elements column-wise. Therefore, you could use either

P = sortrows([A(:), B(:)])

or

P = [B(:) A(:)] %// Thanks @knedlsepp :)

to get sorted combinations.

P now looks like this:

P =

 1     1
 1     2
 1     3
 2     1
 2     2
 2     3
 3     1
 3     2
 3     3

Note that your question is highly related to the following, where the goal is to find combinations from 2 vectors.: How to generate all pairs from two vectors in MATLAB using vectorised code?. I suggest you look at it as well to get more ideas.

That being said the question might be a duplicate...anyhow hope that helps.

Upvotes: 2

Robert Seifert
Robert Seifert

Reputation: 25232

It's a little tricky, as nchoosek can not be used straight out of the box:

n = 3;
X = nchoosek([1:n, n:-1:1],2); 
Y = unique(X,'rows','legacy');

respectively in one line:

Y = unique(nchoosek([1:n, n:-1:1],2),'rows','legacy');

Upvotes: 2

Related Questions