我想创建一个4维网格网格。 我知道我需要使用ngrid函数。但是,除非有一个permute维度,否则meshgrid和ngrid的输出不完全相同。
为了说明,如果完成以下排列,则三维网格网格似乎等同于三维网格:
[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
我想知道4-D网格网格的正确排列是什么。
[X_ndgrid,Y_ndgrid,Z_ndgrid, K_ndgrid] = ndgrid(1:3,4:6,7:9,10:12 )
编辑:EBH,谢谢你的答案如下。只是一个快速的问题。如果endgoal是为了使用interpn创建一个网格,那么用meshgrid创建一个网格或者用ndgrid创建一个网格会有什么区别(假设有三维问题?)
答案 0 :(得分:2)
meshgrid
和ndgrid
之间的区别在于meshgrid
按列排序第一个输入向量,第二个按行排序,因此:
>> [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
虽然ndgrid
以相反的方式命令他们,例如:
>> [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
在前两个维度之后,它们之间没有区别,因此仅在前两个维度上使用permute
就足够了。所以对于4个维度,你只需写:
[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.
它会返回:
ans =
1
ans =
1
ans =
1
如果您想将其用作interpn
,you should use the ndgrid
format。