Ron Bakker/MathLabHelp
Open MathLab ↗

Tutorial · Beginner · 8 min

Surfaces in 3D

From a formula to a shaded, rotatable 3D surface — and the same data as a contour map.

  1. A grid of points

    meshgrid turns two vectors into grids X and Y, so you can compute Z for every point at once.

    [X, Y] = meshgrid(-2:1:2, -1:1:1)
    Try it ↗
    X = 3×5
      -2  -1   0   1   2
      -2  -1   0   1   2
      -2  -1   0   1   2
    Y = 3×5
      -1  -1  -1  -1  -1
       0   0   0   0   0
       1   1   1   1   1
  2. Your first surface

    Compute Z with element-wise operations and pass all three to surf. Drag the figure to rotate it, scroll to zoom, double-click to reset.

    [X, Y] = meshgrid(linspace(-2, 2, 50));
    Z = X .* exp(-X.^2 - Y.^2);
    surf(X, Y, Z)
    colorbar
    Try it ↗
  3. Colours and camera

    Choose a colormap (viridis, plasma, coolwarm …), remove the grid lines with shading flat, and set the camera angle with view(azimuth, elevation).

    [X, Y] = meshgrid(linspace(-3, 3, 70));
    surf(X, Y, peaks(X, Y))
    colormap plasma
    shading flat
    view(-60, 35)
    title('peaks, from another angle')
    xlabel('x'), ylabel('y'), zlabel('z')
    Try it ↗
  4. The same data as a map

    Contours are often clearer in a paper than a 3D view. contourf fills between levels; axis equal keeps distances true.

    [X, Y] = meshgrid(linspace(-3, 3, 150));
    contourf(X, Y, peaks(X, Y), 14)
    colormap viridis
    axis equal
    title('peaks as filled contours')
    Try it ↗