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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With