Surfaces & Contours
A function of two variables, z = f(x, y), is a landscape: hills where it is large, valleys where it is small. MATLAB can draw that landscape as a 3-D surface, or flatten it into a contour map like the height lines on a hiking map. Both start from the same thing: a grid of x-y points and the value of z at each one.
| Function | Draws |
|---|---|
mesh(X, Y, Z) |
Wireframe surface: coloured grid lines, see-through faces |
surf(X, Y, Z) |
Surface with coloured faces and black edges |
surfc, meshc |
The surface plus a contour map underneath |
contour(X, Y, Z) |
Contour lines (curves of equal z) in 2-D |
contourf(X, Y, Z) |
Filled contours: bands of colour between the lines |
contour3(X, Y, Z) |
Contour lines drawn at their height in 3-D |
quiver(X, Y, U, V) |
Arrows of a vector field, often drawn on top of contours |
Step 1: build the grid with meshgrid
Plotting functions want matrices X, Y and Z of the same size, where (X(i,j), Y(i,j)) is one grid point and Z(i,j) the height there. meshgrid builds X and Y from two vectors; then you evaluate the formula with element-wise operators (.*, ./, .^) so it is applied at every point at once:
x = -2:0.2:2; % 21 values
y = -2:0.2:2;
[X, Y] = meshgrid(x, y);
Z = X .* exp(-X.^2 - Y.^2);
fprintf('X, Y and Z are %d-by-%d\n', size(Z, 1), size(Z, 2));
[zmax, k] = max(Z(:));
[zmin, j] = min(Z(:));
fprintf('Highest grid point: %.4f at (%.1f, %.1f)\n', zmax, X(k), Y(k));
fprintf('Lowest grid point: %.4f at (%.1f, %.1f)\n', zmin, X(j), Y(j));X, Y and Z are 21-by-21
Highest grid point: 0.4218 at (0.8, 0.0)
Lowest grid point: -0.4218 at (-0.8, 0.0)
max(Z(:)) flattens the matrix into one column so a single index k comes back; because X and Y have the same shape as Z, X(k) and Y(k) give the coordinates of that point. The true peak of this function is at x = 1/√2 ≈ 0.707 with height 0.4289, so the grid, with points every 0.2, slightly misses it. A finer grid gets closer, at the cost of more points to draw.
Tip: a common mistake is
Z = X * exp(-X^2 - Y^2). Without the dots,*and^are matrix operations and give the wrong answer (or an error).
mesh and surf
Once Z exists, one call draws it. The colour of each face follows its height through the current colormap, and colorbar shows the scale:
[X, Y] = meshgrid(-2:0.2:2); % one vector: the same values for x and y
Z = X .* exp(-X.^2 - Y.^2);
surf(X, Y, Z)
xlabel('x'); ylabel('y'); zlabel('z')
title('z = x e^{-x^2-y^2}')
colorbarmesh(X, Y, Z) takes the same inputs and draws only the grid lines (with white faces that hide what's behind them, unless you also call hidden off). The look of surf changes with shading:
| Command | Effect |
|---|---|
shading faceted |
Default: one colour per face, black edges |
shading flat |
One colour per face, no edges (good for fine grids) |
shading interp |
Colours blended smoothly across each face |
lighting gouraud + camlight |
Adds a light source and smooth shading, for a realistic look |
surf(Z) without X and Y also works: it uses the column and row numbers as coordinates. The built-in peaks function returns a classic test landscape with three hills and two valleys, handy for trying these options: [X, Y, Z] = peaks(30); surf(X, Y, Z).
Contour lines
A contour line connects points where the function has the same value. contour(X, Y, Z) chooses about ten levels automatically; contour(X, Y, Z, n) asks for n levels and contour(X, Y, Z, v) draws exactly the levels in the vector v. contourf fills the bands between lines, and clabel writes the level numbers on the lines:
[X, Y] = meshgrid(-2:0.05:2);
Z = X .* exp(-X.^2 - Y.^2);
levels = -0.4:0.1:0.4;
[C, h] = contourf(X, Y, Z, levels);
clabel(C, h) % label the lines with their values
axis equal
colorbar
xlabel('x'); ylabel('y')Contour maps make it easy to measure a landscape. A point is above a level if Z > level, so the fraction of the grid above it estimates how much of the area lies inside that contour:
[X, Y] = meshgrid(-2:0.05:2);
Z = X .* exp(-X.^2 - Y.^2);
for level = [0.1 0.2 0.3 0.4]
inside = Z > level;
fprintf('z > %.1f on %5.2f%% of the square\n', level, 100 * mean(inside(:)));
endz > 0.1 on 18.55% of the square
z > 0.2 on 10.01% of the square
z > 0.3 on 4.80% of the square
z > 0.4 on 0.98% of the square
The first output of contour and contourf, C, is a contour matrix that stores every line as a header column [level; numberOfPoints] followed by the points' coordinates. You rarely read it yourself, but contourc(x, y, Z, levels) computes the same matrix without drawing anything, which is useful when you need the curve coordinates in a calculation.
surfc(X, Y, Z) combines both views: the surface with its contour map projected onto the floor of the axes.
Arrows on a map: gradient and quiver
The gradient of f points uphill, in the direction of steepest increase, and is always perpendicular to the contour lines. gradient(Z, h) estimates it numerically from the grid (with spacing h) by central differences, and returns the x- and y-components as two matrices. quiver(X, Y, U, V) draws them as arrows:
[X, Y] = meshgrid(-2:0.25:2);
Z = X .* exp(-X.^2 - Y.^2);
[U, V] = gradient(Z, 0.25); % spacing 0.25 in both directions
contour(X, Y, Z, 10)
hold on
quiver(X, Y, U, V)
hold off
axis equalHow good is the numerical estimate? Compare it with the exact partial derivatives at one point, (0.8, 0.2), on three grids of decreasing spacing:
x0 = 0.8; y0 = 0.2;
for h = [0.2 0.1 0.05]
x = -2:h:2;
[X, Y] = meshgrid(x);
Z = X .* exp(-X.^2 - Y.^2);
[U, V] = gradient(Z, h);
i = find(abs(x - x0) < 1e-9); % column of x0
j = find(abs(x - y0) < 1e-9); % row of y0
fprintf('h = %.2f: (%8.4f, %8.4f)\n', h, U(j, i), V(j, i));
end
dzdx = (1 - 2*x0^2) * exp(-x0^2 - y0^2);
dzdy = -2*x0*y0 * exp(-x0^2 - y0^2);
fprintf('exact: (%8.4f, %8.4f)\n', dzdx, dzdy);h = 0.20: ( -0.1218, -0.1559)
h = 0.10: ( -0.1368, -0.1605)
h = 0.05: ( -0.1406, -0.1617)
exact: ( -0.1419, -0.1621)
Each time the spacing h is halved, the error of the central difference shrinks to about a quarter (it is proportional to h²); the Numerical Differentiation lesson explains why. Note the index order: U(j, i) is row j (the y direction) and column i (the x direction), which matches meshgrid, where x changes along a row. Points are found with a tolerance, abs(x - x0) < 1e-9, rather than x == x0, because a value such as 0.8 built by repeatedly adding 0.1 is not exactly 0.8 in binary floating point.
Plotting a formula directly (MATLAB)
Newer MATLAB versions can plot a function handle without a grid: fsurf(@(x, y) x.*exp(-x.^2 - y.^2), [-2 2 -2 2]) and fcontour(...) choose the points themselves and refine where the surface curves. Octave 11 doesn't have fsurf, fmesh or fcontour; it offers the older ezsurf and ezcontour, which take the same inputs. The meshgrid approach above works everywhere and gives you the numbers as well as the picture.
Summary
- Build the grid with
[X, Y] = meshgrid(x, y)and computeZwith element-wise operators. surfandmeshdraw the landscape in 3-D;shadingand lighting change its look;colorbarexplains the colours.contour/contourfdraw lines or bands of equal height,clabellabels them, andcontourcreturns the line coordinates.gradient+quivershow the uphill direction, which is perpendicular to the contours.
Next: Annotations & Text. Learn more: Matplotlib contour plots do the same job in Python.
Test yourself
After [X, Y] = meshgrid(1:4, 1:3), what is size(X)?
[4 3][3 4][1 4][12 1]
Why must you write Z = X .* exp(-X.^2 - Y.^2) with dots?
- Dots make the code run faster
- The formula must be applied element by element at each grid point
- Dots are required inside
exp - Without dots the plot is drawn in 2-D
Which function draws coloured bands between contour levels?
contourcontour3contourfclabel