Converting rectangular grids to an array

8 次查看(过去 30 天)
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.

采纳的回答

David Goodmanson
David Goodmanson 2017-8-24
编辑:David Goodmanson 2017-8-24
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 个评论
Alex
Alex 2017-8-24
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 2017-8-24
Why so pointlessly complex? See my answer to know how simple this really is.

请先登录,再进行评论。

更多回答(1 个)

Stephen23
Stephen23 2017-8-24
编辑:Stephen23 2017-8-25
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
>>

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by