Converting rectangular grids to an array

5 ビュー (過去 30 日間)
Alex
Alex 2017 年 8 月 24 日
編集済み: Stephen23 2017 年 8 月 25 日
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 Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by