MATLAB 3D plot
Welcome to mathresearcher.com! If you have ever felt that 2D charts just aren’t enough to capture the complexity of your data, you are in the right place. In this comprehensive guide, we move beyond the basics to master the MATLAB 3D plot. We will walk you through creating professional-grade Gaussian surfaces, intricate parametric ribbons, and multi-layered point clouds. Whether you are a student visualizing calculus or a researcher clustering high-dimensional data, these step-by-step instructions and “copy-paste-ready” codes will help you create publication-quality figures. If you haven’t started yet, you can download MATLAB from the official MathWorks website to follow along with our examples.
3D Gaussian Surface with Oscillations: Matlab 3d plot
Visualizing mathematical functions in 3D is a core strength of MATLAB. Below, we break down the code required to generate a complex surface that combines a Gaussian distribution with trigonometric oscillations.
Step 1: Setting up the Canvas
figure(‘Position’, [100, 100, 800, 600]);
This line initializes a new graphics window. The ‘Position’ vector defines the window’s location (100 pixels from the left and bottom of your screen) and its size (800×600 pixels).
Step 2: Creating the Coordinate Grid
[X, Y] = meshgrid(-2:0.1:2, -2:0.1:2);
In MATLAB, we cannot simply plot a continuous function; we must evaluate it at discrete points. meshgrid creates a 2D grid of coordinates from -2 to 2. The 0.1 step size determines the “resolution”—smaller values result in a smoother surface but require more memory.
Step 3: Calculating the Z-Values (The Math)
Z = X .* exp(-X.^2 – Y.^2) + 0.5 * sin(2*X) .* cos(3*Y);
This is the heart of the visualization. We are calculating the height (Z) for every (X, Y) pair.
The Formula: $Z = X \cdot e^{-(X^2 + Y^2)} + 0.5 \cdot \sin(2X) \cdot \cos(3Y)$
Note the use of the dot operator (.* and .^). This tells MATLAB to perform element-wise multiplication, ensuring the operation is applied to every point in the grid individually.
Step 4: Rendering the Surface
surf(X, Y, Z, ‘EdgeColor’, ‘none’, ‘FaceAlpha’, 0.9);
The surf command creates the 3D colored surface. We set ‘EdgeColor’ to ‘none’ to remove the black wireframe lines for a cleaner look, and ‘FaceAlpha’ to 0.9 to make the surface slightly translucent.
Step 5: Color and Legend
colormap(jet);
c = colorbar(‘EastOutside’);
We apply the jet colormap (ranging from blue for low values to red for high values). The colorbar adds a vertical scale on the right side of the plot to translate colors into numerical values.
Step 6: Lighting and Materiality
light(‘Position’, [1, 1, 5]);
lighting gouraud;
material shiny;
To make the plot look realistic, we add a virtual light source. lighting gouraud calculates the color across the surfaces smoothly, and material shiny adds specular highlights (reflections) to the peaks.
Complete Source Code
% 1. Create Figure
figure(‘Position’, [100, 100, 800, 600]);
% 2. Define Domain
[X, Y] = meshgrid(-2:0.1:2, -2:0.1:2);
% 3. Calculate Mathematical Function
Z = X .* exp(-X.^2 – Y.^2) + 0.5 * sin(2*X) .* cos(3*Y);
% 4. Plot Surface
surf(X, Y, Z, ‘EdgeColor’, ‘none’, ‘FaceAlpha’, 0.9);
% 5. Styling & Color
colormap(jet);
c = colorbar(‘EastOutside’);
set(get(c, ‘Title’), ‘String’, ‘Function Value’, ‘FontSize’, 11, ‘FontWeight’, ‘bold’);
% 6. Labels
title(‘3D Gaussian Surface with Oscillations’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’);
xlabel(‘X-axis’, ‘FontSize’, 12, ‘FontWeight’, ‘bold’);
ylabel(‘Y-axis’, ‘FontSize’, 12, ‘FontWeight’, ‘bold’);
zlabel(‘Z-axis’, ‘FontSize’, 12, ‘FontWeight’, ‘bold’);
% 7. Final Polish
grid on;
light(‘Position’, [1, 1, 5], ‘Style’, ‘infinite’);
lighting gouraud;
material shiny;
view(45, 30);

Matlab 3d plot: Parametric Spiral Ribbons
In this tutorial, we move beyond simple surfaces to create a Parametric Ribbon. Instead of just plotting a line in 3D space, we calculate the mathematical “normal” to that line to give it width and physical presence, creating a ribbon-like effect.
Step 1: Defining the Spiral Path
t = 0:0.01:8*pi;
x = exp(-0.05*t) .* sin(t);
y = exp(-0.05*t) .* cos(t);
z = t/4;
We define our spiral using a parameter t. The equations for x and y include a decaying exponential $e^{-0.05t}$, which causes the spiral to “shrink” inward over time, while z grows linearly to give the spiral height.
Step 2: Calculating Tangent Vectors
dx = gradient(x); dy = gradient(y); dz = gradient(z);
To orient a ribbon, we first need to know which direction the curve is “pointing” at any given moment. The gradient function calculates the derivative of our coordinates, giving us the Tangent Vector at every point along the path.
Step 3: Creating the Binormal Vector
binormal_x = dy * up(3) – dz * up(2);
binormal_y = dz * up(1) – dx * up(3);
binormal_z = dx * up(2) – dy * up(1);
A ribbon needs width. To find the “sideways” direction relative to our curve, we calculate the Cross Product of our tangent vector and an “up” vector [0, 0, 1]. This resulting Binormal Vector tells MATLAB exactly which way to stretch the surface to create the ribbon’s flat face.
Step 4: Generating the Ribbon Surface
[S, T_idx] = meshgrid(s, 1:num_points);
We use a loop to iterate through every point on our spiral. For each point, we project outward along the Binormal vector to create a set of coordinates (X_ribbon, Y_ribbon, Z_ribbon). This effectively “sweeps” a 2D line along our 3D path, transforming a 1D line into a 2D surface.
Step 5: Multi-Layered Plotting
surf(X_ribbon, Y_ribbon, Z_ribbon, ‘EdgeColor’, ‘none’, ‘FaceAlpha’, 0.8);
scatter3(x(1:200:end), y(1:200:end), z(1:200:end), 40, ‘filled’, ‘MarkerFaceColor’, ‘r’, ‘MarkerEdgeColor’, ‘k’);
plot3(x, y, z, ‘k-‘, ‘LineWidth’, 1);
This plot is actually composed of three layers:
- Surf: Draws the main colored ribbon using the hsv colormap.
- Scatter3: Adds red markers at specific intervals to highlight discrete data points.
- Plot3: Draws a black “center line” through the middle of the ribbon for better definition.
Complete MATLAB Source Code
% 1. Setup Environment
figure(‘Position’, [100, 100, 800, 600]);
t = 0:0.01:8*pi;
% 2. Define Spiral Geometry
x = exp(-0.05*t) .* sin(t);
y = exp(-0.05*t) .* cos(t);
z = t/4;
% 3. Calculate Ribbon Orientation (Vector Calculus)
ribbonwidth = 0.1;
num_points = length(t);
dx = gradient(x); dy = gradient(y); dz = gradient(z);
norm_tangent = sqrt(dx.^2 + dy.^2 + dz.^2);
dx = dx ./ norm_tangent; dy = dy ./ norm_tangent; dz = dz ./ norm_tangent;
% Cross Product with [0,0,1] to find binormal (side-vector)
up = [0, 0, 1];
binormal_x = dy * up(3) – dz * up(2);
binormal_y = dz * up(1) – dx * up(3);
binormal_z = dx * up(2) – dy * up(1);
norm_binormal = sqrt(binormal_x.^2 + binormal_y.^2 + binormal_z.^2);
binormal_x = binormal_x ./ norm_binormal;
binormal_y = binormal_y ./ norm_binormal;
binormal_z = binormal_z ./ norm_binormal;
% 4. Build Ribbon Mesh via Interpolation
s = -ribbonwidth:ribbonwidth/10:ribbonwidth;
[S, T_idx] = meshgrid(s, 1:num_points);
X_ribbon = zeros(size(S)); Y_ribbon = zeros(size(S)); Z_ribbon = zeros(size(S));
for i = 1:size(S, 1)
idx = round(T_idx(i, 1));
X_ribbon(i, 🙂 = x(idx) + binormal_x(idx) .* S(i, :);
Y_ribbon(i, 🙂 = y(idx) + binormal_y(idx) .* S(i, :);
Z_ribbon(i, 🙂 = z(idx) + binormal_z(idx) .* S(i, :);
end
% 5. Rendering & Aesthetics
surf(X_ribbon, Y_ribbon, Z_ribbon, ‘EdgeColor’, ‘none’, ‘FaceAlpha’, 0.8);
colormap(hsv); shading interp;
hold on;
scatter3(x(1:200:end), y(1:200:end), z(1:200:end), 40, ‘filled’, ‘MarkerFaceColor’, ‘r’, ‘MarkerEdgeColor’, ‘k’);
plot3(x, y, z, ‘k-‘, ‘LineWidth’, 1);
% 6. Labels and Viewpoint
title(‘Parametric Spiral with Ribbon Visualization’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’);
xlabel(‘X-axis’); ylabel(‘Y-axis’); zlabel(‘Z-axis’);
grid on; light(‘Position’, [-1, -1, 1]); lighting gouraud;
view(45, 20);
legend(‘Ribbon’, ‘Data Points’, ‘Center Line’, ‘Location’, ‘NorthEast’);

Matlab 3D Plot: Data Clustering, Visualizing 3D Synthetic Datasets
In data science and research, visualizing how data points group together is crucial. This tutorial demonstrates how to generate and plot three distinct types of synthetic clusters: Spherical, Linear, and Ring-shaped.
Step 1: Reproducibility and Initialization
figure('Position', [100, 100, 850, 650]);
n = 500;
rand('seed', 42);
We define n = 500 points per cluster. Setting the seed ensures that every time you run this code, the “random” points are generated in the exact same positions—essential for consistent research results.
Step 2: Generating the Spherical Cluster
theta1 = 2*pi*rand(n,1);
phi1 = pi*rand(n,1);
x1 = 2*sin(phi1).*cos(theta1) + randn(n,1)*0.1;
y1 = 2*sin(phi1).*sin(theta1) + randn(n,1)*0.1;
z1 = 2*cos(phi1) + randn(n,1)*0.1;
To create a sphere, we use spherical coordinates transformed into Cartesian coordinates (X, Y, Z).
The Math: x = r · sin(φ) · cos(θ).
We add a small amount of Gaussian noise (randn * 0.1) so the points don’t sit perfectly on the surface, giving it a realistic “cloud” feel.
Step 3: Creating Linear Cluster
x2 = randn(n,1)*1.5 + 4;
y2 = randn(n,1)*0.5 + 4;
z2 = 0.5*x2 + randn(n,1)*0.3;
For the Linear Cluster, we create points that follow a linear relationship. The x-values are centered around 4 with more spread, the y-values are more tightly clustered, and z is linearly related to x with some noise. This creates a stretched, line-like cluster in 3D space.
Step 4: Creating Ring Cluster
theta3 = 2*pi*rand(n,1);
x3 = 3*cos(theta3) + randn(n,1)*0.2;
y3 = 3*sin(theta3) + randn(n,1)*0.2;
z3 = randn(n,1)*0.5 - 2;
For the Ring Cluster, we use polar coordinates (sine and cosine) to create points in a circular pattern. The x and y coordinates form a ring with radius 3, while the z-coordinate is clustered around -2 with some vertical spread, creating a flattened ring shape.
Step 5: Advanced 3D Scattering
scatter3(x1, y1, z1, 50, 'r', 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k');
hold on;
scatter3(x2, y2, z2, 50, 'b', '^', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k');
scatter3(x3, y3, z3, 50, 'g', 's', 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'k');
The scatter3 function is used to plot individual points. To make the clusters distinct, we use different properties:
- Red Circles: Spherical cluster.
- Blue Triangles (
'^'): Linear cluster. - Green Squares (
's'): Ring cluster. - MarkerEdgeColor: We add a black (‘k’) edge to each point to make them stand out against the white background.
- Size (50): Controls the marker size for better visibility.
Step 6: Transparency and Proportions
h = findobj(gca, 'Type', 'patch');
for i = 1:length(h)
alpha(h(i), 0.7);
end
We use alpha to make the points 70% opaque. This allows you to see “through” the clusters to see points hidden in the middle.
Step 7: Labels and Final Touches
title('3D Scatter Plot of Synthetic Clusters', 'FontSize', 14, 'FontWeight', 'bold');
xlabel('Feature X'); ylabel('Feature Y'); zlabel('Feature Z');
grid on; view(45, 20);
legend('Spherical Cluster', 'Linear Cluster', 'Ring Cluster', 'Location', 'Best');
axis equal;
Finally, we add labels, a grid for better spatial orientation, set a nice viewing angle, create a legend, and use axis equal to ensure proper proportions—this prevents the sphere from looking like an oval by making all axes use the same scale.
Complete MATLAB Source Code
% 1. Initialization
figure('Position', [100, 100, 850, 650]);
n = 500;
rand('seed', 42);
% 2. Dataset 1: Spherical cluster
theta1 = 2*pi*rand(n,1);
phi1 = pi*rand(n,1);
x1 = 2*sin(phi1).*cos(theta1) + randn(n,1)*0.1;
y1 = 2*sin(phi1).*sin(theta1) + randn(n,1)*0.1;
z1 = 2*cos(phi1) + randn(n,1)*0.1;
% 3. Dataset 2: Linear cluster
x2 = randn(n,1)*1.5 + 4;
y2 = randn(n,1)*0.5 + 4;
z2 = 0.5*x2 + randn(n,1)*0.3;
% 4. Dataset 3: Ring cluster
theta3 = 2*pi*rand(n,1);
x3 = 3*cos(theta3) + randn(n,1)*0.2;
y3 = 3*sin(theta3) + randn(n,1)*0.2;
z3 = randn(n,1)*0.5 - 2;
% 5. Plotting with Markers
scatter3(x1, y1, z1, 50, 'r', 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'k');
hold on;
scatter3(x2, y2, z2, 50, 'b', '^', 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'k');
scatter3(x3, y3, z3, 50, 'g', 's', 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'k');
% 6. Applying Transparency
h = findobj(gca, 'Type', 'patch');
for i = 1:length(h)
alpha(h(i), 0.7);
end
% 7. Labels & Finishing
title('3D Scatter Plot of Synthetic Clusters', 'FontSize', 14, 'FontWeight', 'bold');
xlabel('Feature X'); ylabel('Feature Y'); zlabel('Feature Z');
grid on; view(45, 20);
legend('Spherical Cluster', 'Linear Cluster', 'Ring Cluster', 'Location', 'Best');
axis equal;

Frequently Asked Questions (FAQ)
1. Why do we need the meshgrid function for 3D surfaces?
meshgrid function takes two linear vectors and transforms them into a 2D matrix. Without this, MATLAB wouldn’t know which Z-value corresponds to which (X, Y) pair on a surface.2. How can I make my 3D plots look smoother?
-2:0.1:2, the step is 0.1. If you change this to 0.01, the surface will look much smoother, but it will use more memory and take longer to render.3. What is the difference between “shading interp” and “shading faceted”?
shading faceted (the default) shows the black grid lines between the colored patches. shading interp (interpolated) removes those lines and blends the colors smoothly across each face, which is ideal for organic shapes like the parametric ribbon.4. Why do we use “axis equal” in the scatter plot example?
axis equal forces the X, Y, and Z axes to use the same physical scale, which is essential for accurate geometric visualization.5. What are the Tangent and Binormal vectors used for?
6. How do I change the color of my 3D plot?
colormap command. Popular options include:colormap(hot)– Black-Red-Yellowcolormap(winter)– Blue and Greencolormap(gray)– Black and Whitecolormap(parula)– The modern MATLAB default (blue to yellow)