How to Use Mesh in MATLAB: Syntax, Example, and Tips
In MATLAB, use the
mesh function to create a 3D mesh plot of surface data defined by matrices X, Y, and Z. The syntax is mesh(X,Y,Z), where X and Y define the grid coordinates and Z defines the height values. This visualizes data as a wireframe surface.Syntax
The basic syntax for the mesh function is:
mesh(Z): Creates a mesh plot using matrixZwith default X and Y coordinates.mesh(X,Y,Z): Uses matricesXandYto specify the grid coordinates andZfor heights.mesh(..., 'PropertyName', PropertyValue): Customize the mesh appearance with properties like color and edge style.
matlab
mesh(X,Y,Z) % where % X, Y: matrices of the same size defining grid coordinates % Z: matrix of the same size defining surface heights
Example
This example creates a mesh plot of the function z = sin(sqrt(x^2 + y^2)) over a grid.
matlab
x = -5:0.5:5; y = -5:0.5:5; [X,Y] = meshgrid(x,y); Z = sin(sqrt(X.^2 + Y.^2)); mesh(X,Y,Z) title('3D Mesh Plot of z = sin(sqrt(x^2 + y^2))') xlabel('X axis') ylabel('Y axis') zlabel('Z axis')
Output
A 3D wireframe mesh plot window appears showing a ripple surface shaped by the sine function.
Common Pitfalls
Common mistakes when using mesh include:
- Using vectors instead of matrices for
X,Y, andZ. Usemeshgridto create coordinate matrices. - Passing
Zwith a different size thanXandY. All must be the same size. - Confusing
meshwithsurf.meshcreates a wireframe, whilesurfcreates a colored surface.
matlab
x = -5:5; y = -5:5; Z = sin(sqrt(x.^2 + y.^2)); % Incorrect: Z is vector, not matrix mesh(x,y,Z) % This will cause an error % Correct way: [X,Y] = meshgrid(x,y); Z = sin(sqrt(X.^2 + Y.^2)); mesh(X,Y,Z)
Quick Reference
| Syntax | Description |
|---|---|
| mesh(Z) | Plot mesh using Z with default X and Y coordinates |
| mesh(X,Y,Z) | Plot mesh with specified grid coordinates X, Y and heights Z |
| mesh(..., 'EdgeColor', 'r') | Set mesh edge color to red |
| mesh(..., 'FaceColor', 'none') | Make mesh faces transparent (wireframe) |
| mesh(..., 'LineStyle', '--') | Change mesh line style to dashed |
Key Takeaways
Use mesh(X,Y,Z) with coordinate matrices X, Y and height matrix Z for 3D wireframe plots.
Create grid matrices X and Y using meshgrid before calling mesh.
Ensure X, Y, and Z are the same size to avoid errors.
mesh creates a wireframe surface, different from surf which creates a colored surface.
Customize mesh appearance with properties like 'EdgeColor' and 'LineStyle'.