1

I would like to enumerate grid points in a N x m matrix, where N is the number of grid points and m is the number of dimensions in the grid. For a 2D grid (i.e., m=2), this I can accomplish this with:

a = -1:1;
b = -2:2;
[A,B] = meshgrid(a,b);
c=cat(2,A',B');
d=reshape(c,[],2);
d

where d is a 15 x 2 matrix.

How do I to this in higher dimensions after generating the grid points with ndgrid? For example:

[A, B, C] = ndgrid(-1:1, -2:2, 0:3);

In this example, I want to convert the elements of A,B,C to a 60 x 3 matrix.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Adam
  • 997
  • 2
  • 12
  • 21
  • Placing points into a 2-column matrix inherently means that each row is a 2D point. Using `ndgrid` in your second case provides 3D points. Do you mean a `60 x 3` matrix, not `60 x 2`? You have an extra degree of freedom when calling `ndgrid` with three vectors as you will produce 3D points... so where does the loss of dimension (3D -> 2D) go? For the sake of understanding you better, please provide a physical example given input points and what the expected output `N x 2` matrix looks like. – rayryeng Aug 23 '15 at 22:29
  • Realized this mistake immediately after posting and just edited. I meant a `60 x 3` matrix. – Adam Aug 23 '15 at 22:34
  • Is `d=[A(:) B(:) C(:)]` what you want? Anyway, the problem with that is you need to rewrite the code if the number of dimensions varies. For a more general approach that avoids that see [here](http://stackoverflow.com/questions/21895335/generate-a-matrix-containing-all-combinations-of-elements-taken-from-n-vectors) – Luis Mendo Aug 23 '15 at 22:34
  • @LuisMendo - I think that merits marking as a duplicate. – rayryeng Aug 23 '15 at 22:40

0 Answers0