How to Use Contour in MATLAB: Syntax and Examples
In MATLAB, use the
contour function to create contour plots that show lines of constant values for a matrix. You provide X and Y coordinates along with a matrix Z of values, and MATLAB draws contour lines representing levels in Z.Syntax
The basic syntax for the contour function is:
contour(Z): Draws contour lines for matrix Z with default X and Y coordinates.contour(X, Y, Z): Uses X and Y matrices or vectors to specify coordinates for Z.contour(X, Y, Z, N): Draws N contour levels.contour(X, Y, Z, levels): Draws contour lines at specifiedlevels(vector of values).
You can also customize colors and line styles by adding name-value pairs.
matlab
contour(Z) contour(X, Y, Z) contour(X, Y, Z, N) contour(X, Y, Z, levels)
Example
This example creates a contour plot of a simple function Z = X^2 + Y^2 over a grid. It shows how to use contour with X, Y, and Z matrices and specify the number of contour levels.
matlab
x = -2:0.1:2; y = -2:0.1:2; [X, Y] = meshgrid(x, y); Z = X.^2 + Y.^2; contour(X, Y, Z, 10) title('Contour plot of Z = X^2 + Y^2') xlabel('X axis') ylabel('Y axis')
Output
A contour plot window showing 10 contour lines forming concentric circles centered at (0,0).
Common Pitfalls
Common mistakes when using contour include:
- Not matching the sizes of X, Y, and Z matrices. They must be the same size if X and Y are matrices.
- Using vectors X and Y that do not match the dimensions of Z.
- Passing a scalar instead of a vector for contour levels.
- Forgetting to use element-wise operators like
.^when computing Z.
Always check matrix sizes with size() before plotting.
matlab
x = -2:0.1:2; y = -2:0.1:2; Z = x.^2 + y.^2; % Incorrect: Z is 1D vector contour(x, y, Z) % This will error because sizes mismatch % Correct way: [X, Y] = meshgrid(x, y); Z = X.^2 + Y.^2; contour(X, Y, Z)
Quick Reference
Tips for using contour in MATLAB:
- Use
meshgridto create X and Y matrices for 2D functions. - Specify contour levels as a vector for precise control.
- Use
clabelto add labels to contour lines. - Customize colors with
colormapand line styles with additional arguments.
Key Takeaways
Use
contour(X, Y, Z) with matching X, Y, Z sizes to plot contour lines.Specify the number or exact values of contour levels to control plot detail.
Always create X and Y grids with
meshgrid for 2D functions.Check matrix dimensions to avoid size mismatch errors.
Use
clabel to label contour lines for better readability.