Matlab

MATLAB – meshgrid vs ndgrid

The MATLAB meshgrid() function can be used to obtain 2-D, 3-D, or, n-D meshgrid. We can swap the meshgrid by using the MATLAB ndgrid() function. In this article, we will learn how to swap meshgrid in MATLAB with the help of an example.

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.

x = [-1:2:4];

y = [11:2:15];

[X,Y] = meshgrid(x,y)

Now we will use the ndgrid() function to swap the rows and columns of the above-created meshgrid.

x = [-1:2:4];

y = [11:2:15];

[X,Y] = ndgrid(x,y)

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.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.