agf1997
agf1997

Reputation: 2898

Converting rectangular grids to an array in matlab

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 27x3)? 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 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.

Upvotes: 3

Views: 103

Answers (1)

jodag
jodag

Reputation: 22314

The following code gives you the array you describe.

nx = [1 2 3];
ny = [4 5 6];
nz = [7 8 9];

[x_mesh, y_mesh, z_mesh] = ndgrid(nx, ny, nz);

grid = reshape(permute([x_mesh; y_mesh; z_mesh],[3 2 1]),[],3);

To iterate on x first, then y, then z you can just use

grid = [x_mesh(:) y_mesh(:) z_mesh(:)]

A generic solution which gives you more direct control over the order of iteration is

order = [1 3 2];
grid = reshape(permute(cat(4,x_mesh,y_mesh,z_mesh),[order 4]),[],3)

Which iterates on x first, then z, then y.

Upvotes: 3

Related Questions