Reputation: 1144
I want to create a 4 dimensional meshgrid. I know I need to use the ngrid function. However, the output of meshgrid and ngrid is not exactly the same unless one permutes dimensions.
To illustrate, a three dimensional meshgrid seems to be equivalent to a three dimensional ngrid if the following permutations are done:
[X_ndgrid,Y_ndgrid,Z_ndgrid] = ndgrid(1:3,4:6,7:9)
X_meshgrid = permute(X_ndgrid,[2,1,3]);
Y_meshgrid = permute(Y_ndgrid,[2,1,3]);
Z_meshgrid = permute(Z_ndgrid,[2,1,3]);
sum(sum(sum(X == X_meshgrid))) == 27
sum(sum(sum(Y == Y_meshgrid))) == 27
sum(sum(sum(Z == Z_meshgrid))) == 27
I was wondering what are the right permutations for a 4-D meshgrid.
[X_ndgrid,Y_ndgrid,Z_ndgrid, K_ndgrid] = ndgrid(1:3,4:6,7:9,10:12 )
Edit: EBH, thanks for your answer below. Just one more quick question. If the endgoal is to create a grid in order to use interpn, what would be the difference between creating a grid with meshgrid or with ndgrid (assuming a 3 dimensional problem?)
Upvotes: 2
Views: 2055
Reputation: 10440
The difference between meshgrid
and ndgrid
is that meshgrid
order the first input vector by the columns, and the second by the rows, so:
>> [X,Y] = meshgrid(1:3,4:6)
X =
1 2 3
1 2 3
1 2 3
Y =
4 4 4
5 5 5
6 6 6
while ndgrid
order them the other way arround, like:
>> [X,Y] = ndgrid(1:3,4:6)
X =
1 1 1
2 2 2
3 3 3
Y =
4 5 6
4 5 6
4 5 6
After the first 2 dimensions, there is no difference between them, so using permute
only on the first 2 dimensions should be enough. So for 4 dimensions you just write:
[X_ndgrid,Y_ndgrid,Z_ndgrid,K_ndgrid] = ndgrid(1:3,4:6,7:9,10:12);
[X_meshgrid,Y_meshgrid,Z_meshgrid] = meshgrid(1:3,4:6,7:9);
X_meshgrid_p = permute(X_meshgrid,[2,1,3]);
Y_meshgrid_p = permute(Y_meshgrid,[2,1,3]);
all(X_ndgrid(1:27).' == X_meshgrid_p(:)) % the transpose is only relevant for this comparison, not for the result.
all(Y_ndgrid(1:27).' == Y_meshgrid_p(:)) % the transpose is only relevant for this comparison, not for the result.
all(Z_ndgrid(1:27).' == Z_meshgrid(:)) % the transpose is only relevant for this comparison, not for the result.
and it will return:
ans =
1
ans =
1
ans =
1
If you want to use it as an input for interpn
, you should use the ndgrid
format.
Upvotes: 2