Converting rectangular grids to an array

조회 수: 12 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by