MATLAB: Converting rectangular grids to an array

MATLABmeshgridndgrid

I'm using ndgrid to create a series of rectangular grids. For example :
nx = [1 2 3];
ny = [4 5 6];
nz = [7 8 9];
[x_mesh, y_mesh, z_mesh] = ndgrid(nx, ny, nz);
Is there a simple way to convert the coordinates of the rectangular grids to a NxM array (in this case 27×3)? The result should look like this:
[1,4,7;
1,4,8;
1,4,9;
1,5,7;
1,5,8;
1,5,9;
1,6,7;
1,6,8;
1,6,9;
...
3,6,7;
3,6,8;
3,6,9]
If possible, I'd like to specify the direction in which to compile the coordinates in the array. For example, the above moves along z, then y, then x. It'd be nice if one could specify to move in the order x, then y, then z instead.

Best Answer

Hi Alex,
The concatenation
m = [x_mesh(:) y_mesh(:) z_mesh(:)]
gives a 27x3 list of all the points, but not in the order you prefer. Doing some permutations on indices works:
xx = permute(x_mesh,[3 2 1]);
zz = permute(z_mesh,[3 2 1]);
m = [xx(:) y_mesh(:) zz(:)]