MATLAB - Plot Spectrogram
Visualizing Signals with Spectrograms in MATLAB
Section titled “Visualizing Signals with Spectrograms in MATLAB”A spectrogram is a powerful tool for visualizing the frequency content of a signal as it changes over time. It’s essential in fields like audio processing, communications, and vibration analysis. MATLAB’s Signal Processing Toolbox™ provides the spectrogram function to easily compute and display these insightful plots.
What is a Spectrogram?
Section titled “What is a Spectrogram?”A spectrogram is a 3D plot displayed as a 2D image. It shows:
- Time on the x-axis.
- Frequency on the y-axis.
- Signal Power/Magnitude as the color intensity at each time-frequency point.
It’s generated by computing the Short-Time Fourier Transform (STFT), which involves breaking the signal into small, overlapping time windows and calculating the Fourier transform for each window.
The spectrogram Function
Section titled “The spectrogram Function”The primary syntax for generating and plotting a spectrogram is:
spectrogram(x, window, noverlap, nfft, fs, 'yaxis')Let’s break down the key parameters:
x: Your input signal vector.window: A vector defining the windowing function (e.g.,hamming(256)). This shapes the signal segments to reduce spectral leakage. The window length determines the trade-off between time and frequency resolution.noverlap: The number of samples that overlap between consecutive windows. A typical value is 50% of the window length, which ensures smooth transitions.nfft: The number of points for the Fast Fourier Transform (FFT). A largernfftprovides finer frequency resolution.fs: The sampling frequency of the signal. This is crucial for correctly labeling the frequency axis in Hertz.'yaxis': An optional argument that plots the spectrogram directly with time on the x-axis and frequency on the y-axis.
Key Concept: The Time-Frequency Trade-off
- A short window provides good time resolution (you can pinpoint when a frequency event occurs) but poor frequency resolution (it’s hard to distinguish between two close frequencies).
- A long window provides good frequency resolution but poor time resolution.
Practical Examples
Section titled “Practical Examples”Example 1: A Chirp Signal
Section titled “Example 1: A Chirp Signal”A chirp signal is perfect for demonstrating a spectrogram because its frequency changes over time. Let’s create a signal that sweeps from 100 Hz to 400 Hz.
% --- Signal Parameters ---samplingFreq = 1000; % Hzduration = 2; % secondstimeVector = 0:1/samplingFreq:duration-1/samplingFreq;
% --- Create a linear chirp signal ---initialFreq = 100; % HzfinalFreq = 400; % HzchirpSignal = chirp(timeVector, initialFreq, duration, finalFreq, 'linear');
% --- Spectrogram Parameters ---windowLength = 256; % samplesoverlap = round(0.5 * windowLength); % 50% overlapnfft = 512; % FFT points
% --- Generate and Plot Spectrogram ---figure;spectrogram(chirpSignal, hamming(windowLength), overlap, nfft, samplingFreq, 'yaxis');title('Spectrogram of a Linear Chirp Signal');
% Add a colorbar to show power levelscolorbar;The resulting plot will clearly show a diagonal line, starting at 100 Hz at t=0 and rising to 400 Hz at t=2, visually confirming the signal’s changing frequency content.
Example 2: Analyzing a Sum of Sines
Section titled “Example 2: Analyzing a Sum of Sines”Now, let’s analyze a signal composed of two distinct sine waves, one of which appears only for a short duration.
samplingFreq = 1000; % HztimeVector = 0:1/samplingFreq:2-1/samplingFreq;
% A 50 Hz sine wave present for the whole durationsine1 = sin(2 * pi * 50 * timeVector);
% A 200 Hz sine wave present only from t=0.5s to t=1.5ssine2 = sin(2 * pi * 200 * timeVector);sine2(timeVector < 0.5 | timeVector > 1.5) = 0; % Gating the signal
combinedSignal = sine1 + sine2;
% --- Generate and Plot Spectrogram ---figure;spectrogram(combinedSignal, 128, 120, 128, samplingFreq, 'yaxis');title('Spectrogram of a Gated Sinusoid');colorbar;The spectrogram for this example will show two horizontal lines. One line will be at 50 Hz, spanning the entire 2-second duration. The second, brighter line will appear at 200 Hz, but only between the 0.5 and 1.5-second marks, demonstrating the spectrogram’s ability to localize signals in both time and frequency.
Common Errors & Practical Tips
Section titled “Common Errors & Practical Tips”- Error:
Undefined function 'spectrogram': This means the Signal Processing Toolbox™ is not installed or not active. You can install it from the Add-Ons menu. - Plot looks ‘smeared’ or ‘blocky’: Your time-frequency resolution is not well-matched to your signal. Experiment with the
windowLength. A shorter window improves time resolution (less smearing); a longer window improves frequency resolution (less blockiness in frequency). - Frequency axis is incorrect: You likely forgot to provide the correct sampling frequency
fsas an argument to thespectrogramfunction. Without it, the y-axis will be in normalized frequency. - Interactive Analysis: For interactive exploration, use
pspectrum(signal, fs, 'spectrogram'). This creates a plot where you can zoom, pan, and measure peaks without regenerating the spectrogram.