Skip to content

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.

% Modern Recommended Syntax
mesh(X, Y, Z)
surf(X, Y, Z)
% Additional Options
mesh(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. Z is a matrix defining the height at each point on the grid defined by matrices X and Y. The color of the wireframe lines is typically proportional to the height Z.
  • 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 matrix Z as 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 for surf as well.
  • s = mesh(...): Returns a chart surface object. This handle s allows you to programmatically modify the plot’s properties after it has been created, which is a key best practice for advanced plotting.

Let’s explore these concepts with updated, runnable code examples.

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 data
Z = peaks(X, Y);
% 3. Create two plots to compare mesh and surf
figure; % Create a new figure window
% Subplot 1: Mesh plot
subplot(1, 2, 1); % Create a 1x2 grid of plots, and use the 1st one
mesh(X, Y, Z);
title('Mesh Plot of peaks()');
xlabel('X-axis');
ylabel('Y-axis');
% Subplot 2: Surface plot
subplot(1, 2, 2); % Use the 2nd plot in the grid
surf(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.

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 origin
R = sqrt(X.^2 + Y.^2) + eps; % Add eps to avoid division by zero at origin
% Calculate the Sinc function
Z = sin(R) ./ R;
% Create the surface plot
figure;
surf(X, Y, Z);
% Add labels and a color bar for context
title('3D Sinc Function');
xlabel('X');
ylabel('Y');
zlabel('Z');
colorbar; % Shows the mapping of color to Z-value

Example 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 effect
light;
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 shiny

Explanation: '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.

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.

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.

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.

  • Matrix Dimension Mismatch: The most common error. The dimensions of X, Y, and Z must match. Use size(X), size(Y), and size(Z) to check them before plotting. meshgrid is the standard way to ensure they match.
  • Forgetting Element-wise Operators: When defining Z from a function of X and Y, 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 Z matrix contains all the same values (or NaN), the plot will appear flat. Check the calculation of Z.