MATLAB: Create a vector ,of sets of predefined numbers stored in another row vectors

matrixvectors

Guys,I have two row vectors X=[3:6] and Y=[8:27].I want to create and store all possible combinations of (X,Y) in another vector ,say Z.
So my Z will be, Z=[(3,8) (3,9) (3,10)…(3,27) (4,8) (4,9)……(6,26) (6,27)]

Best Answer

This is called the Cartesian product of the two sets.
A fairly straightforward way is to use ndgrid:
x = 3:6;
y = 8:27;
[xx, yy] = ndgrid(x, y);
cartprod = [xx(:) yy(:)]
This works also for more than two vectors:
x = 3:6;
y = 8:27;
z = 2:2:8;
[xx, yy, zz] = ndgrid(x, y, z);
cartprod = [xx(:) yy(:) zz(:)]