What Is Meshgrid in MATLAB?

By Joe Friedman

MATLAB is a handy mathematical software package for carrying out calculations ranging from simple arithmetic and calculus to linear algebra and signal processing. It can also plot data in graphs. MATLAB’s thousands of built-in functions give it its power, and one of its powerful plotting tools is the “meshgrid” function. The function puts user-defined grid lines into two-dimensional and three-dimensional graphs.

MATLAB Plotting Defaults

When using any of the 2-D plotting functions in MATLAB on their own with no additional instruction, MATLAB will not use grid lines. If the user plots a graph in 2-D space, the background area of the plot is blank and white. In 3-D space, MATLAB will use a generic grid. If grid lines of any kind need to show up on a 2-D graph to make its appearance clearer, the user must specify that when calling the plot command or from the figure window after MATLAB generates the graph.

Meshgrid Versus Grid

MATLAB’s “grid” function is a simple way to turn on generic grid lines in 2-D when calling a plot. A pre-programmed algorithm in MATLAB determines how many grid lines to use and how far apart to space them. In contrast, the user completely determines the horizontal and vertical grid lines that appear on a graph when using the “meshgrid” function. Additionally, the number of grid lines and their spacing is the same for both axes with “grid,” but with “meshgrid” the user could require, for example, three grid lines horizontally and 100 grid lines vertically.

3-D Example

Here is an example using “meshgrid” for a three-dimensional plot.[X,Y] = meshgrid(-2:.2:2, -1:0.2:1)Z = X .* exp(-X.^2 - Y.^2);surf(X,Y,Z)The first line of code tells MATLAB to use horizontal gridlines ranging from -2 to 2, with spacings of 0.2. It also requires vertical gridlines from -1 to 1 in steps of tenths. The second line tells MATLAB how to calculate the “Z” value based on the “X” and “Y” values. Lastly, MATLAB’s “surf” function plots a 3-D surface suspended in space, with the meshgrid conformed to the surface.

Another 3-D Example

Here is another way to use “meshgrid” for a three-dimensional plot.[X,Y] = meshgrid(-2:.2:2)Z = X .* exp(-X.^2 - Y.^2);surf(X,Y,Z)The second and third lines are identical to the previous section, but in this case, the "meshgrid" function only took one argument. MATLAB understands that receiving only one argument actually means the user is telling the program to use the same number of grid lines and spacings for the "X" and "Y" values. With this code, the surface will have 21 horizontal grid lines as well as 21 vertical grid lines, all equally spaced.