Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting rectangular grids to an array in matlab

Tags:

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.

like image 577
agf1997 Avatar asked Sep 15 '26 17:09

agf1997


1 Answers

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.

like image 137
jodag Avatar answered Sep 18 '26 12:09

jodag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!