Converting rectangular grids to an array

15 views (last 30 days)
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 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.

Accepted Answer

David Goodmanson
David Goodmanson on 24 Aug 2017
Edited: David Goodmanson on 24 Aug 2017
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(:)]
  2 Comments
Alex
Alex on 24 Aug 2017
Thanks David ... ended up with a very similar solution
order = [1 3 2];
grid = reshape(permute(cat(4,x_mesh,y_mesh,z_mesh),[order 4]),[],3)
Stephen23
Stephen23 on 24 Aug 2017
Why so pointlessly complex? See my answer to know how simple this really is.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 24 Aug 2017
Edited: Stephen23 on 25 Aug 2017
All you really need to do is use the correct order of arguments to ndgrid:
>> nx = [1 2 3];
>> ny = [4 5 6];
>> nz = [7 8 9];
>> [z_mesh,y_mesh,x_mesh] = ndgrid(nz,ny,nx);
>> m = [x_mesh(:),y_mesh(:),z_mesh(:)]
m =
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
2 4 7
2 4 8
2 4 9
2 5 7
2 5 8
2 5 9
2 6 7
2 6 8
2 6 9
3 4 7
3 4 8
3 4 9
3 5 7
3 5 8
3 5 9
3 6 7
3 6 8
3 6 9
>>

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!