Tutorial · Beginner · 8 min
Surfaces in 3D
From a formula to a shaded, rotatable 3D surface — and the same data as a contour map.
A grid of points
meshgridturns two vectors into gridsXandY, so you can computeZfor every point at once.
Try it ↗[X, Y] = meshgrid(-2:1:2, -1:1:1)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
Your first surface
Compute
Zwith element-wise operations and pass all three tosurf. Drag the figure to rotate it, scroll to zoom, double-click to reset.
Try it ↗[X, Y] = meshgrid(linspace(-2, 2, 50)); Z = X .* exp(-X.^2 - Y.^2); surf(X, Y, Z) colorbarColours and camera
Choose a colormap (
viridis,plasma,coolwarm…), remove the grid lines withshading flat, and set the camera angle withview(azimuth, elevation).
Try it ↗[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')The same data as a map
Contours are often clearer in a paper than a 3D view.
contourffills between levels;axis equalkeeps distances true.
Try it ↗[X, Y] = meshgrid(linspace(-3, 3, 150)); contourf(X, Y, peaks(X, Y), 14) colormap viridis axis equal title('peaks as filled contours')