Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I obtain a single array from all possible combinations of the elements of two vectors?

Tags:

arrays

matlab

I have two vectors:

 x = [1 2 3]; y = [4 5]

I need a single array yx that gives me one-to-one combinations of the elements of both vectors. This is the code I have tried so far using of the examples from Stackoverflow.

sets  = {y, x};
[y x] = ndgrid(sets{:});
yx    = [y x]'

This gives me the result:

yx =

 4     5
 4     5
 4     5
 1     1
 2     2
 3     3

Whereas, I am expecting the following result:

yx =

 4     1
 4     2
 4     3
 5     1
 5     2
 5     3

Please, what am I doing wrong here? Any help/suggestions is greatly appreciated. Thanks!

like image 971
oma11 Avatar asked Feb 06 '23 05:02

oma11


1 Answers

What you're trying to obtain is a cartesian product of the two vector. Here's a solution:

>> x = [1 2 3]; y = [4 5];

>> [X,Y] = meshgrid(y,x);

>> result = [X(:) Y(:)]
result =

   4   1
   4   2
   4   3
   5   1
   5   2
   5   3

(this works also in Octave and does not require extra libraries)

like image 196
user2314737 Avatar answered Feb 08 '23 17:02

user2314737