# What Is Meshgrid in MATLAB?

Techwalla may earn compensation through affiliate links in this story.

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.