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

227 views (last 30 days)
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?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Oct 2013
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 Comment
Stephen23
Stephen23 on 11 May 2023
Edited: Stephen23 on 11 May 2023
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

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!