How to Use surf in MATLAB for 3D Surface Plots
In MATLAB, use the
surf function to create 3D surface plots by passing matrices for X, Y, and Z coordinates. It visualizes data as a colored surface, helping you see relationships between variables in three dimensions.Syntax
The basic syntax of surf is:
surf(Z): Creates a surface plot using matrixZfor height values, with X and Y as indices.surf(X,Y,Z): Uses matricesXandYfor coordinates andZfor height.surf(..., C): Specifies color dataCfor the surface.
This function plots a 3D colored surface where colors represent height or specified data.
matlab
surf(Z) surf(X,Y,Z) surf(X,Y,Z,C)
Example
This example creates a 3D surface plot of the function z = sin(sqrt(x^2 + y^2)). It shows how to generate X and Y grids, compute Z, and plot with surf.
matlab
x = linspace(-5,5,50); y = linspace(-5,5,50); [X,Y] = meshgrid(x,y); Z = sin(sqrt(X.^2 + Y.^2)); surf(X,Y,Z) title('3D Surface plot of z = sin(sqrt(x^2 + y^2))') xlabel('X axis') ylabel('Y axis') zlabel('Z axis')
Output
A 3D colored surface plot window appears showing wave-like surface with axes labeled X, Y, Z.
Common Pitfalls
Common mistakes when using surf include:
- Passing vectors instead of matrices for
X,Y, andZ. Usemeshgridto create coordinate matrices. - Not matching the sizes of
X,Y, andZ. All must be the same size. - Using
surfwith very large matrices can slow down rendering.
matlab
x = -5:5; y = -5:5; % vectors % Z = sin(sqrt(x.^2 + y.^2)); % error: sizes mismatch % Correct way: [X,Y] = meshgrid(x,y); Z = sin(sqrt(X.^2 + Y.^2)); surf(X,Y,Z)
Quick Reference
| Usage | Description |
|---|---|
| surf(Z) | Surface plot with Z heights, X and Y as indices |
| surf(X,Y,Z) | Surface plot with specified X, Y coordinates |
| surf(X,Y,Z,C) | Surface plot with color data C |
| meshgrid(x,y) | Create coordinate matrices for X and Y |
| xlabel('label') | Label X axis |
| ylabel('label') | Label Y axis |
| zlabel('label') | Label Z axis |
| title('text') | Add title to plot |
Key Takeaways
Use surf with matrices X, Y, and Z to create 3D surface plots in MATLAB.
Generate coordinate grids with meshgrid to match sizes of X, Y, and Z.
Colors on the surface represent height or specified color data.
Always label axes and add titles for clear visualization.
Avoid size mismatches and large matrices for better performance.