Rectangular grid in N-D space


[X1,X2,X3,...,Xn] = ndgrid(x1gv,x2gv,x3gv,...,xngv)
[X1,X2,...,Xn] = ndgrid(xgv)


[X1,X2,X3,...,Xn] = ndgrid(x1gv,x2gv,x3gv,...,xngv) replicates the grid vectors x1gv,x2gv,x3gv,...,xngv to produce a full grid. This grid is represented by the output coordinate arrays X1,X2,X3,...,Xn. The ith dimension of any output array Xi contains copies of the grid vector xigv.

[X1,X2,...,Xn] = ndgrid(xgv) is the same as [X1,X2,...,Xn] = ndgrid(xgv,xgv,...,xgv). In other words, you can reuse the same grid vector in each respective dimension. The dimensionality of the output arrays is determined by the number of output arguments.

The coordinate arrays [X1,X2,X3,...,Xn] are typically used to evaluate functions of several variables and to create surface and volumetric plots.

Input Arguments


Grid vector specifying a series of grid point coordinates in the ith dimension.


Generic grid vector specifying a series of point coordinates.

Output Arguments


The ith dimension of the output array Xi are copies of elements of the grid vector xigv. The output arrays specify the full grid.


collapse all

Evaluate Function Over Gridded Domain

Evaluate the function $x_1 e^{-x_1^2-x_2^2}$ over the gridded domain $-2<x_1<2$ and $-2<x_2<2$.

Create a grid of values for the domain.

[X1,X2] = ndgrid(-2:.2:2, -2:.2:2);

Evaluate the function over the domain.

Z = X1 .* exp(-X1.^2 - X2.^2);

Generate a mesh plot of the function.


More About

expand all


The ndgrid function is similar to meshgrid, however ndgrid supports 1-D to N-D while meshgrid is restricted to 2-D and 3-D. The coordinates output by each function are the same, but the shape of the output arrays in the first two dimensions are different. For grid vectors x1gv, x2gv and x3gv of length M, N and P respectively, ndgrid(x1gv, x2gv) will output arrays of size M-by-N while meshgrid(x1gv, x2gv) outputs arrays of size N-by-M. Similarly, ndgrid(x1gv, x2gv, x3gv) will output arrays of size M-by-N-by-P while meshgrid(x1gv, x2gv, x3gv) outputs arrays of size N-by-M-by-P. See Grid Representation in the MATLAB® Mathematics documentation for more information.

Introduced before R2006a

Was this topic helpful?