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

combinationselementsmatrixpairsrepetitionvectorswithout

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

Best 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.