What is the difference between the NDGRID and MESHGRID functions in MATLAB?

144 次查看(过去 30 天)
What is the difference between the NDGRID and MESHGRID functions in MATLAB?
I need to create gridded data points from sets of vectors. I don't understand the difference between NDGRID and MESHGRID. Why do they produce the same outputs, but in a different order?

采纳的回答

MathWorks Support Team
The main difference between the outputs of MESHGRID and NDGRID has to do with how data is visualized. MESHGRID produces data that is oriented in Cartesian coordinates, generally a more expected view. For example, if I use the command:
[X,Y] = meshgrid(1:3,4:6)
The output is:
>>X =
1 2 3
1 2 3
1 2 3
>>Y =
4 4 4
5 5 5
6 6 6
We expect the x values to be changing horizontally, and the y values to be changing vertically. That is the output MESHGRID produces.
In the case of NDGRID, the data produced is related to the dimension order. In MATLAB, the row dimension is the first dimension, and the the column dimension is the second dimension. In that case, the first vector input to NDGRID will be replicated and oriented in the direction of the first dimension, i.e. moving vertically across the rows. The second vector input will move in the direction of the second dimension, so it will go across the columns.
[X,Y] = ndgrid(1:3,4:6)
produces the output:
>>X =
1 1 1
2 2 2
3 3 3
>>Y =
4 5 6
4 5 6
4 5 6
Only the first two outputs from MESHGRID and NDGRID will be different. The other outputs will be the same.
For 3D data sets, conversion from MESHGRID format to NDGRID format (and vice versa) can be done transposing each X-Y slice of the 3D arrays. This can be easily accomplished using the PERMUTE command in the following manner:
[X_ndgrid,Y_ndgrid,Z_ngrid] = 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]);
Summary:
NDGRID is to be used for higher dimensionality use and for when you want the results to reflect matrix/array notation:
MESHGRID is to be used for visualizing data and should be used primarily for when plotting two or three dimensional data.
  1 个评论
Stephen23
Stephen23 2023-5-11
编辑:Stephen23 2023-5-11
Better examples using non-square matrices:
[X,Y] = meshgrid(1:3,4:7)
X = 4×3
1 2 3 1 2 3 1 2 3 1 2 3
Y = 4×3
4 4 4 5 5 5 6 6 6 7 7 7
[X,Y] = ndgrid(1:3,4:7)
X = 3×4
1 1 1 1 2 2 2 2 3 3 3 3
Y = 3×4
4 5 6 7 4 5 6 7 4 5 6 7

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by