# How to find all possible combinations between the numbers of two vectors where order does matter

5 views (last 30 days)
Commented: KostasK on 9 Sep 2021
I have the following two vectors
a = [1 2 3 4]
b = [2 4]
and I would like to find all possible combination between the numbers of these two vectors, but order does matter. So a valid combination would be [1 2] as well as [2 1], thus yielding two results for each of those cases. So using my vectors a and b what I would like to get is:
c = [2 1
2 2
2 3
2 4
4 1
4 2
4 3
4 4
1 2
1 4
3 2
3 4] ;
Notice that rows 1:8 on the above can be returned by using either combvec(a, b), or the simple method:
[m, n] = ndgrid(a, b) ;
Z = [m(:), n(:)]
However I am struggling to find out how to make a code to create the last four rows. Thanks for your help in advance

the cyclist on 9 Sep 2021
I expect there is a more efficient way, but I think this will do what you want.
a = [1 2 3 4];
b = [2 4];
c = unique([combvec(a,b)'; combvec(b,a)'],'row');
disp(c)
1 2 1 4 2 1 2 2 2 3 2 4 3 2 3 4 4 1 4 2 4 3 4 4
yep, that works!