What is difference between stem and plot in MATLAB?
Vectorized implementations, execution benchmarks, and step-by-step programming documentation.
In MATLAB, both the plot and stem functions are used to visualize data curves, but they represent data in fundamentally different formats:
plotfunction: Displays continuous data values by connecting data points with straight line segments. Think of drawing the graph ofy = sin(x)smoothly with a pencil without lifting it from the paper.stemfunction: Displays discrete data values by drawing vertical stems extending from the baseline (x-axis) to each data point with a marker at the top. Think of plottingy = sin(x)for specific angles (such as 0°, 15°, 30°, 45°, 60°, and 90°) and drawing individual vertical lines from the x-axis to each point.
MATLAB Code Example: Continuous vs. Discrete Visualization
Run the following MATLAB code to compare plot and stem side-by-side using subplots:
clc;
clear all;
close all;
% Generate 50 points linearly spaced between -pi and pi x = linspace(-pi, pi, 50);
y = sin(x);
% Subplot 1: Continuous representation using
plot() sub
plot(1, 2, 1);
plot(x, y, 'b-', 'LineWidth', 1.5);
xticks([-pi 0 pi]);
xticklabels({'-pi', '0', 'pi'});
title('Continuous Plot:
plot(x, y)');
xlabel('x (radians)');
ylabel('sin(x)');
grid on;
% Subplot 2: Discrete representation using stem() sub
plot(1, 2, 2);
stem(x, y, 'r', 'LineWidth', 1.2, 'MarkerFaceColor', 'r');
xticks([-pi 0 pi]);
xticklabels({'-pi', '0', 'pi'});
title('Discrete Stem Plot: stem(x, y)');
xlabel('x (radians)');
ylabel('sin(x)');
grid on;Code Explanation
linspace(-pi, pi, 50)creates a vector of 50 evenly spaced points from-πtoπ.subplot(1, 2, 1)andsubplot(1, 2, 2)divide the figure window into two side-by-side panels.xticksandxticklabelsformat the x-axis tick marks using LaTeX notation (-π,0,π).grid onadds a background grid for better visual clarity.
Conclusion: The plot panel presents a smooth, continuous waveform, whereas the stem panel highlights individual discrete sample points rooted at the baseline.
Need Expert Guidance with MATLAB or Simulink?
Our 500+ PhD engineers provide verified MATLAB code, custom Simulink models, and 1-on-1 tutoring with comprehensive code quality verification.