MATLAB: How do you bring about all possible combinations from two row vectors

output combinations

Say for example I have
x=[1 2 3 4] y=[1 2 3 4]
and I wanted to create a new vector z which would give all combinations of the elements of x and y. It would look something like
z=[(1,1) (1,2) (1,3) (1,4) (2,1) (2,2) (2,3) (2,4) (3,1) etc etc]. Is this even possible?

Best Answer

Yes. Use NDGRID or MESHGRID, e.g.,
>> [x,y]=ndgrid([1,2], [3,4])
x =
1 1
2 2
y =
3 4
3 4
>> z=[x(:),y(:)]
z =
1 3
2 3
1 4
2 4