MATLAB - Plot Mesh Surface
MATLAB - Modern 3D Mesh and Surface Plotting
Section titled “MATLAB - Modern 3D Mesh and Surface Plotting”Visualizing functions of two variables in three-dimensional space is a fundamental task in science and engineering. MATLAB offers powerful tools for this, primarily through its mesh and surf functions. These functions allow you to render complex surfaces, analyze mathematical functions, and present data in an intuitive 3D format.
The mesh function generates a wireframe plot. It’s excellent for viewing the underlying structure and grid of a surface. In contrast, the surf function creates a filled surface plot with colors representing the surface’s height (Z-value), offering a more solid and visually rich representation. A third function, surfc, combines a surface plot with a contour plot underneath, providing two perspectives in a single visualization.
Core Syntax
Section titled “Core Syntax”% Modern Recommended Syntaxmesh(X, Y, Z)surf(X, Y, Z)
% Additional Optionsmesh(Z)mesh(..., Name, Value)s = mesh(...)Let’s break down the modern syntax and its variations:
mesh(X, Y, Z): Creates a 3D wireframe plot.Zis a matrix defining the height at each point on the grid defined by matricesXandY. The color of the wireframe lines is typically proportional to the heightZ.surf(X, Y, Z): Creates a 3D colored surface plot. This is often preferred for final visualizations as it shows a solid surface.mesh(Z): A simplified syntax where MATLAB uses the row and column indices of matrixZas the x and y coordinates. Useful for quick visualizations of matrix data.mesh(..., Name, Value): Customizes the plot’s appearance using name-value pairs. This is the modern, flexible way to control properties like transparency ('FaceAlpha'), color ('FaceColor'), and edge style ('EdgeColor'). This works forsurfas well.s = mesh(...): Returns a chart surface object. This handlesallows you to programmatically modify the plot’s properties after it has been created, which is a key best practice for advanced plotting.
Practical Examples of 3D Plotting
Section titled “Practical Examples of 3D Plotting”Let’s explore these concepts with updated, runnable code examples.
Example 1: Basic mesh and surf Plot
Section titled “Example 1: Basic mesh and surf Plot”The peaks function is a classic MATLAB example of a function of two variables. Let’s visualize it using both mesh and surf to see the difference.
% 1. Define the grid[X, Y] = meshgrid(-3:0.25:3);
% 2. Calculate the height dataZ = peaks(X, Y);
% 3. Create two plots to compare mesh and surffigure; % Create a new figure window
% Subplot 1: Mesh plotsubplot(1, 2, 1); % Create a 1x2 grid of plots, and use the 1st onemesh(X, Y, Z);title('Mesh Plot of peaks()');xlabel('X-axis');ylabel('Y-axis');
% Subplot 2: Surface plotsubplot(1, 2, 2); % Use the 2nd plot in the gridsurf(X, Y, Z);title('Surface Plot of peaks()');xlabel('X-axis');ylabel('Y-axis');Best Practice: Notice the use of figure to create a new window, subplot to arrange multiple plots, and title/xlabel/ylabel to properly label the visualizations. This makes your plots clear and professional.
Example 2: Visualizing the Sinc Function
Section titled “Example 2: Visualizing the Sinc Function”Let’s plot a more complex mathematical function and customize its appearance.
% Define a finer grid for a smoother plot[X, Y] = meshgrid(-8:0.5:8);
% Calculate the distance from the originR = sqrt(X.^2 + Y.^2) + eps; % Add eps to avoid division by zero at origin
% Calculate the Sinc functionZ = sin(R) ./ R;
% Create the surface plotfigure;surf(X, Y, Z);
% Add labels and a color bar for contexttitle('3D Sinc Function');xlabel('X');ylabel('Y');zlabel('Z');colorbar; % Shows the mapping of color to Z-valueExample 3: Customizing Appearance with Name-Value Pairs
Section titled “Example 3: Customizing Appearance with Name-Value Pairs”Modern MATLAB plotting heavily relies on name-value pairs for customization. Let’s make a plot with transparency and without the black grid lines.
[X, Y] = meshgrid(-3:0.2:3);Z = peaks(X,Y);
figure;s = surf(X, Y, Z, ... 'EdgeColor', 'none', ... % Remove the black mesh lines 'FaceColor', 'interp', ... % Smooth the colors across faces 'FaceAlpha', 0.8); % Make the surface 80% opaque
% Add lighting for a more realistic 3D effectlight;lighting gouraud;
title('Customized Surface Plot');xlabel('X');ylabel('Y');
% Pro Tip: Modify properties after creation using the handle 's's.Shininess = 50; % Make the surface a bit more shinyExplanation: 'EdgeColor', 'none' is perfect for creating clean, smooth surfaces. 'FaceAlpha' is essential for visualizing multiple overlapping surfaces. Using the returned handle s to modify properties is a powerful technique for dynamic or complex visualizations.
Surface Plot with Contours (surfc)
Section titled “Surface Plot with Contours (surfc)”The meshc function (mesh with contours) still exists, but its modern counterpart for surface plots is surfc. It projects the contour lines onto the xy-plane, giving you a 2D and 3D view simultaneously.
Syntax
Section titled “Syntax”surfc(X, Y, Z)surfc(X, Y, Z) creates a surface plot with contour lines drawn beneath it. It accepts all the same name-value pair arguments as surf.
Example: surfc in Action
Section titled “Example: surfc in Action”Let’s apply surfc to our peaks data.
[X, Y, Z] = peaks(25);
figure;surfc(X, Y, Z);
title('Surface Plot with Contours');xlabel('X-axis');ylabel('Y-axis');colorbar;Application: This is extremely useful in fields like geography (topographical maps), physics (potential fields), and engineering (stress analysis) where you need to see both the surface elevation and the level curves simultaneously.
Debugging and Common Errors
Section titled “Debugging and Common Errors”- Matrix Dimension Mismatch: The most common error. The dimensions of
X,Y, andZmust match. Usesize(X),size(Y), andsize(Z)to check them before plotting.meshgridis the standard way to ensure they match. - Forgetting Element-wise Operators: When defining
Zfrom a function ofXandY, remember to use element-wise operators (.^,.*,./) so the operation is applied to each element of the matrices. Forgetting this will result in a matrix multiplication error. - Plot is a Flat Plane: If your
Zmatrix contains all the same values (orNaN), the plot will appear flat. Check the calculation ofZ.