All possible combinations of n pairs of 2 elements from 2 vectors of n elements without repetition of the elements
6 views (last 30 days)
Show older comments
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
1 Comment
Azzi Abdelmalek
on 27 Sep 2013
What is the size of the result. Is the expected result only what you posted?
Accepted Answer
Roger Stafford
on 27 Sep 2013
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)
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!