Azzera filtri
Azzera filtri

Converting rectangular grids to an array

9 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

David Goodmanson
David Goodmanson il 24 Ago 2017
Modificato: David Goodmanson il 24 Ago 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 Commenti
Alex
Alex il 24 Ago 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 il 24 Ago 2017
Why so pointlessly complex? See my answer to know how simple this really is.

Accedi per commentare.

Più risposte (1)

Stephen23
Stephen23 il 24 Ago 2017
Modificato: Stephen23 il 25 Ago 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
>>

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by