All possible combinations of n pairs of 2 elements from 2 vectors of n elements without repetition of the elements

I have two vectors of n elements (both the same n) e.g. x=[1 2 3] y=[4 5 6]
I would like an "easy" way to get all the possible combinations of n pairs of 2 elements (one from each vector) without repeating any element, and place them in a matrix.
It's difficult for me to explain it but let's see an example.
From these two vectors x=[1 2 3] y=[4 5 6] I'd like get a matrix with the following rows (the order of them doesn't matter):
1 4 2 5 3 6
1 4 2 6 3 5
1 5 2 4 3 6
1 5 2 6 3 4
1 6 2 4 3 5
1 6 2 5 3 4
It should work with any length of x and y (n)
Thank you in advance

 Accepted Answer

p = perms(y);
[m,n] = size(p);
z = zeros(m,2*n);
z(:,1:2:end-1) = repmat(x,m,1);
z(:,2:2:end) = p;
This assumes the elements of x are not permuted in z, just as in your example.

More Answers (0)

Categories

Find more on Elementary Math in Help Center and File Exchange

Asked:

on 27 Sep 2013

Commented:

on 28 Sep 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!