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

16 visualizaciones (últimos 30 días)
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

Respuesta aceptada

the cyclist
the cyclist el 9 de Sept. de 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

Más respuestas (0)

Categorías

Más información sobre Bounding Regions en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by