What is MATLAB meshgrid() and ndgrid()
The ndgrid() is a built-in MATLAB function that is used for creating 2-D, 3-D, or n-D grids. This function generates data associated with the dimension order. In MATLAB, the first dimension is the row dimension, while the second dimension is the column dimension. In this sense, the first vector input to ndgrid() function will be duplicated and orientated in the first dimension, i.e. moving vertically across the rows. The second vector input will move horizontally across the columns.
In simple words, the ndgrid() function creates a grid by swapping the rows and columns of the meshgrid created by the meshgrid() function.
Example
The given example demonstrates how to swap a meshgrid using ndgrid() in MATLAB. For this first, we create a meshgrid using the MATLAB meshgrid() function.
Now we will use the ndgrid() function to swap the rows and columns of the above-created meshgrid.
Remember that ndgrid() function just swaps the rows and columns of the first two matrices. This means when we have an n-dimensional meshgrid, the ndgrid() function will only swap the rows and columns of the first two created matrices and keep the other matrices unchanged.
Conclusion
The MATLAB meshgrid() function can be used to obtain 2-D, 3-D, or, n-D meshgrid in a way such that each row of the matrix X is a duplicate of x, and each column of the matrix Y is a duplicate of y where X*Y is the Cartesian product of X and Y used for creating a grid to plot a surface where x and y are vectors defining the domain of the function which we need to plot. The MATLAB ndgrid() function is used for swapping the rows and columns of the first two matrices of the meshgrid. This guide taught us how to use ndgrid() function to swap a meshgrid in MATLAB.