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

4 ビュー (過去 30 日間)
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
the cyclist 2021 年 9 月 9 日
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

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by