1

I have got a question regarding all the combinations of matrix-rows in Matlab. I currently have a matrix with the following structure:

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

Now I want to get all the possible combinations of these "pairs" without using a number twice in the same row:

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

And it must be possible to make it with n-"doublecolumns". Which means, when my pair-matrix goes for example until "5 6", i want to create the matrix with 3 of these doublecolumns:

1 2 3 4 5 6
1 2 3 5 4 6
1 2 3 6 4 5
1 3 2 4 5 6
1 3 2 5 4 6
....

I hope you understand what I mean :) Any ideas how to solve this?

Thanks and best regard Jonas

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Krus
  • 83
  • 2
  • 10

1 Answers1

0
M = [1 2 
     1 3
     1 4
     2 3
     2 4
     3 4]; %// example data
n = floor(max(M(:))/2); %// size of tuples. Compute this way, or set manually

p = nchoosek(1:size(M,1), n).'; %'// generate all n-tuples of row indices
R = reshape(M(p,:).', n*size(M,2), []).'; %// generate result...
R = R(all(diff(sort(R.'))),:); %'//...removing combinations with repeated values
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Thanks for your answer. Actually it is exactly what I wanted. My further problem is now the size. Is there a possibility to create this matrix without using the nchoosek-command? Because I'm currently programming an optimising-algorithm which brings as input a vector which could have a length bigger than 15. So the nchoosek-command generates a huge matrix, which will be shortend with the last line. So have you any idea how to program it without generating first this hugh combination-matrix? Thank you in advance... – Krus Mar 28 '14 at 08:41
  • @Krus Maybe using [something like this](http://stackoverflow.com/q/21895335/2586922) (using the same vector `n` times as input) and then removing rows that differ only in their order (with `sort` and `unique`). Anyway that's probably worth a question on its own – Luis Mendo Mar 28 '14 at 10:24