askvity

Understanding the `stem` Function in MATLAB

Published in MATLAB Plotting 3 mins read

What is stem in Matlab?

In MATLAB, stem is a function used to create stem plots, which are specialized graphs for visualizing discrete data sequences.

The stem function is essential for plotting data points that correspond to distinct, separate values along the x-axis, unlike a continuous line plot which is used for data that changes smoothly over time or space. It displays a vertical line (the "stem") from the baseline (typically the x-axis) up to the data point, with a marker at the data point's location.

According to the documentation:

`stem( X , Y ) plots the data sequence, Y , at values specified by X . The X and Y inputs must be vectors or matrices of the same size. Additionally, X can be a row or column vector and Y must be a matrix with length(X) rows.

This means you provide two inputs to the stem function:

  • X: The locations on the x-axis where your data points occur.
  • Y: The actual data values you want to plot at those x-locations.

How stem(X, Y) Works

When you use stem(X, Y):

  1. MATLAB takes each corresponding pair of values from X and Y.
  2. For each pair (x_i, y_i), it draws a vertical line from the x-axis (or a specified baseline) at x_i up to the point (x_i, y_i).
  3. A marker (like a circle or square) is placed at the point (x_i, y_i) to clearly indicate the data value.

This visual representation is particularly useful in fields like digital signal processing or statistics where data is often sampled or exists only at specific intervals.

Practical Use Cases

Stem plots are ideal for:

  • Visualizing discrete-time signals.
  • Showing the values of a sequence (e.g., coefficients of a polynomial, impulse response).
  • Displaying probability mass functions.
  • Comparing discrete data points.

Example (Conceptual)

Imagine you sampled a signal's amplitude at specific time points. You could use stem to plot these samples:

  • X could be a vector of time points: [0, 0.1, 0.2, 0.3, 0.4]
  • Y could be a vector of measured amplitudes at those times: [1.5, 2.1, 1.8, 0.9, 0.5]

Plotting stem(X, Y) would show a stem at each time point (0, 0.1, etc.) reaching up to the corresponding amplitude value.

The flexibility in input types (X and Y being vectors or matrices of the same size, or X a vector and Y a matrix with matching rows) allows for plotting multiple data sequences on the same stem plot or handling data sampled across different series at the same points.

In summary, the stem function in MATLAB is a specialized plotting tool designed to clearly represent discrete data points using a "stem" and marker format, distinct from the continuous lines used in standard plot functions.

Related Articles