The meshgrid() Function in MATLAB

Ammar Ali Nov 15, 2021
The meshgrid() Function in MATLAB

This tutorial will discuss creating a grid using the meshgrid() function in Matlab.

Create a Grid Using the meshgrid() Function in MATLAB

To create 2D and 3D grids in Matlab, we can use Matlab’s built-in function meshgrid(). In Matlab, grids are used to plot data on a 3D plane. To plot a vector or matrix on a 3D plane, we have to create a 2D or 3D grid using the meshgrid() function. In 2D plots, we pass the x and y coordinates as a vector, but in 3D, we have to pass a matrix instead of a vector. We can use the meshgrid() function to convert vectors into matrices which will be used to plot the data in a 3D plane. For example, let’s convert two vectors containing x and y coordinates to matrices using the meshgrid() function. See the code below.

x = 1:4
y = 1:6
[X,Y] = meshgrid(x,y)

Output:

x =

     1     2     3     4


y =

     1     2     3     4     5     6


X =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4


Y =

     1     1     1     1
     2     2     2     2
     3     3     3     3
     4     4     4     4
     5     5     5     5
     6     6     6     6

In the output, we can see the difference between the small x and y and capital X and Y. We cannot use the small x and y coordinates to plot data in a 3D plane, but we can use the capital X and Y coordinates to plot the data in a 3D plane. For example, let’s create a vector to plot on a 3D plane using the X and Y coordinates and the surf() function. See the code below.

x = 1:4;
y = 1:6;
[X,Y] = meshgrid(x,y);
Z = X.^2 + Y.^2;
surf(X,Y,Z)

Output:

3D Plot Using meshgrid

The surf() function is used to plot the matrix Z on a 3D plane. The matrix Z should have the same size as the X and Y matrices. We can also create a 3D grid using three or one input vector and three output variables using the meshgrid() function. The meshgrid() function will create a 3D grid that forms a cube of grid points. If we pass only one input vector in the meshgrid() function, the function will take the other two coordinates from the indices of the first vector.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - MATLAB Plot