Matlab Analyze Spectrum
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Science and research
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to spectral analysis in MATLAB, covering both batch and streaming data processing. It guides users through selecting the appropriate estimator (e.g., pspectrum, pwelch, periodogram, pmtm, pburg) based on signal characteristics like length, uniformity, and spectral content. The skill emphasizes best practices such as proper window selection, unit normalization, and the use of built-in measurement functions for peak detection, bandwidth, and power estimation, while discouraging manual FFT implementations.
What it does
- Recommends spectral estimators based on signal length and character
- Provides workflows for batch and streaming spectral analysis
- Automates peak detection, bandwidth measurement, and power calculation
- Offers guidance on window selection and leakage control
- Supports advanced techniques like multitaper and parametric estimation
- Ensures correct unit normalization and dB conversion
When to use it
- When computing frequency content, PSD, or power spectrum
- When analyzing signal periodicity or resolving close frequencies
- When performing real-time streaming spectral analysis
- When comparing frequency content between two signals
- When measuring band power or occupied bandwidth
Advantages
- Reduces errors by using built-in, calibrated functions
- Provides clear decision trees for estimator selection
- Standardizes spectral visualization and measurement
- Includes verification steps like Parseval's theorem
- Handles complex scenarios like non-uniform sampling
Usage examples
- “How do I compute the PSD of a long signal in MATLAB?”
- The agent will recommend using pwelch for low-variance PSD estimation, providing code to set segment length and windowing for optimal resolution.
- “I need to find the dominant frequency peaks in my signal.”
- The agent will guide you to use findpeaks on the spectral output, including advice on setting prominence and distance thresholds.
- “How can I perform real-time spectral analysis?”
- The agent will direct you to use spectrumAnalyzer or dsp.SpectrumEstimator from the DSP System Toolbox for frame-by-frame processing.
- “Which window should I use to resolve two close frequencies?”
- The agent will suggest using a Hann or Kaiser window and explain the trade-off between main-lobe width and sidelobe suppression.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-analyze-spectrum/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-analyze-spectrum.zip -d .agents/skills
Documentation by MathWorks
Analyze Signal Spectra in MATLAB
Compute, visualize, and extract measurements from signal spectra using Signal Processing Toolbox. Choose the right spectral estimator, avoid common FFT pitfalls, and use built-in measurement functions instead of reinventing them.
When to Use
Computing frequency content of a signal (FFT, periodogram, PSD, power spectrum)
Estimating power spectral density (Welch, periodogram, parametric)
Comparing frequency content of two signals (cross-spectrum, coherence)
Finding spectral peaks (dominant frequencies, harmonics)
Measuring bandwidth, band power, or occupied bandwidth
Visualizing frequency-domain data
Streaming (real-time, frame-by-frame) spectral analysis with
spectrumAnalyzer,dsp.SpectrumEstimator,dsp.CrossSpectrumEstimator
When NOT to Use
Designing or applying filters -- use
matlab-design-digital-filterTime-frequency/spectrogram analysis (including
spectrumAnalyzerspectrogram ViewType, STFT, reassignment, CWT) -- use the time-frequency analysis skill (TBD)Audio-specific features (MFCC, pitch, auditory models) -- use Audio Toolbox
Control system frequency response (Bode, Nyquist) -- use Control System Toolbox
Workflow
Batch or streaming? -- Determine if data is already in workspace (batch) or arrives frame-by-frame (streaming). See below.
Preliminary analysis -- When user provides data, run diagnostics to inform technique selection (see below)
Pre-process -- Check for NaN/gaps (use
plombfor non-uniform data). Applydetrend(x)only if DC/trend visibly distorts the spectrumChoose output type -- PSD, power spectrum, amplitude spectrum, or octave bands (see below)
Choose estimator -- Use preliminary analysis results + Estimator Selection below
Compute spectrum -- Use the chosen function with explicit
Fs(if available)Visualize -- Plot with proper axis labels (Hz, dB or linear units)
Extract metrics -- Use
findpeaks,bandpower,obw,powerbw. Seereferences/peak-detection.mdVerify -- Parseval's theorem, known tone levels. See
references/power-from-spectrum.md
Batch vs Streaming
Determine the processing mode before choosing tools:
| Indicator | Mode | Tools |
|---|---|---|
| Entire signal in workspace (vector/matrix) | Batch | pwelch, pspectrum, periodogram, pburg, etc. |
| Data arrives frame-by-frame (sensor, ADC, real-time loop) | Streaming | spectrumAnalyzer, dsp.SpectrumEstimator, dsp.CrossSpectrumEstimator |
| Need live-updating spectrum display | Streaming | spectrumAnalyzer (ViewType: spectrum) |
| Need spectrum values for real-time decisions | Streaming | dsp.SpectrumEstimator (returns numeric output each frame) |
If streaming: See references/streaming-spectral-analysis.md for System object APIs, properties, and patterns. DSP System Toolbox is required.
The rest of this skill covers batch processing. For streaming, the reference file provides full guidance including the batch-to-streaming mapping table.
Preliminary Data Analysis
When the user provides signal data (variable, file, or description), run diagnostic checks before recommending a technique. See references/preliminary-analysis.md for full code.
Quick checks (run in order — stop early if decisive):
Sampling type — Fs given → uniform. Time vector with small jitter (<5%) →
pspectrum(x,t)(resamples internally). Large jitter or truly non-uniform →plombData quality — NaN/Inf, DC offset, trend → preprocess first
Length — <128: parametric only. 128–1024:
periodogram/pburg. >10k:pwelchpreferredSpectral character — Run
periodogram(Hann), compute spectral flatness + peak count + strongest peak width:Flatness >0.3 → wideband →
pwelch(peaks are just noise fluctuations)Flatness <0.1, strongest peak narrow (width < 10×df) → tonal →
periodogram(...,'power')orrootmusicFlatness <0.1, strongest peak wide (width ≥ 10×df) → wideband-structured (chirps, shaped bands) →
pwelch+obwFlatness 0.1–0.3, peaks present → mixed →
pwelch+findpeaks
AR fitness — Fit AR models with
arburg, track prediction error vs order. If error plateaus <10% at low order →pburgis strong candidateTone count — If tonal: count peaks with
findpeaks, cross-check with eigenvalue drop. Known count + resolution-limited →rootmusic(x,2*nTones,Fs)
Report findings to the user before computing the spectrum:
Preliminary Analysis:
- Sampling: uniform at [Fs] Hz
- Duration: [X] s ([N] samples), resolution: [df] Hz
- Spectral character: [wideband/tonal/mixed]
- AR fit: [quality] (order [N], residual [X]%)
Recommendation: [estimator] because [justification]Output Type Selection
| User's Goal | Output Type | Function / Option |
|---|---|---|
| Compare to a standard or another signal (length-independent) | PSD (power/Hz) | pwelch (default), periodogram |
| Read amplitude of a specific tone | Power spectrum → sqrt | pspectrum(x,Fs) (default); periodogram(x,w,N,Fs,'power') or pwelch(x,w,[],[],Fs,'power') for explicit control |
| Measure total power in a band | PSD then integrate, or use bandpower | bandpower(x,Fs,[fLow fHigh]) |
| Octave-band levels (acoustics, vibration) | Fractional-octave spectrum | poctave(x,Fs,'BandsPerOctave',3) |
| Detect frequencies in nearly-uniform data (small jitter) | Power spectrum | pspectrum(x,t) — resamples internally |
| Detect frequencies in non-uniform/gapped data | Lomb-Scargle | plomb(x,t) |
PSD vs Power Spectrum: PSD (power/Hz) is resolution-independent — broadband noise stays flat when you change parameters. Power spectrum (power/bin) is tone-friendly — peak height equals true tone power. Use PSD for noise characterization and specs (g²/Hz, dBm/Hz); use power spectrum for reading tone amplitudes. Convert: PS = PSD × RBW where RBW = enbw(win)*Fs/segLen.
Estimator Selection
Decision tree (simple → specialized):
Just want to see what frequencies are present? →
pspectrum(x,Fs)Need a smooth, low-variance PSD? →
pwelch(favored for long signals — segment averaging reduces variance) orperiodogram(short signal, cannot segment)Need accurate tone amplitude from peaks? →
periodogram(x,win,N,Fs,'power')thensqrtNeed octave-band levels (acoustics, vibration)? →
poctave(x,Fs,'BandsPerOctave',3)Comparing two signals at each frequency? →
mscohere(related?) /cpsd(shared content + phase)Data is nearly uniform (small jitter)? →
pspectrum(x,t)(resamples internally). Truly non-uniform or large gaps? →plomb(x,t)Need to resolve sinusoids closer than Fs/N? →
rootmusic/pmusic(must know # of sinusoids)Short data, want low-variance PSD without segmenting? →
pmtm(multitaper — uses orthogonal DPSS tapers on full record; no AR assumption)Short data, want smooth sidelobe-free PSD? →
pburg(assumes signal is AR-like)
Quick reference table:
| Goal | Function | When to use |
|---|---|---|
| Quick look at frequency content | pspectrum | Default -- good defaults, tune Leakage (0–1) for resolution vs sidelobes |
| Single-sided amplitude spectrum | periodogram with 'power' | Need amplitude per bin |
| PSD with low variance | pwelch | Long signals — averaging segments reduces variance; preferred when signal is long enough to segment |
| PSD of short signal, low variance | pmtm | Multitaper — uses full record with orthogonal DPSS tapers; no segmentation needed |
| PSD of short signal | periodogram | Too short to segment; high variance (single window) |
| Resolve closely-spaced sinusoids | pmusic, rootmusic | Known # of sinusoids, super-resolution |
| Smooth PSD of short AR-like data | pburg | No sidelobes; NOT for resolving tones |
Default: Start with pspectrum. Drop to pwelch/periodogram for explicit control. Never use manual FFT unless user explicitly asks — redirect to built-in functions.
pspectrum vs pwelch: pspectrum outputs power spectrum (Kaiser beta=20, ~76% overlap). pwelch defaults to PSD. They match within ~0.2 dB using equivalent parameters. See references/pspectrum-equivalence.md for exact mapping. Resolution control in pspectrum: Use FrequencyResolution (Hz) to set target resolution directly, or Leakage (0–1) to control the resolution/sidelobe trade-off indirectly. TimeResolution is spectrogram-only — do NOT use it for power spectrum. Leakage parameter: pspectrum(x,Fs,Leakage=L) where L ∈ [0,1] — 0 = minimum leakage (max sidelobe suppression, widest main lobe), 1 = maximum leakage (rectangular window, best resolution), default 0.5.
Nonparametric vs Parametric: Use nonparametric (FFT-based) when signal is long or spectral shape is unknown. Use parametric when data is short, signal matches an AR model, or you need super-resolution. See references/estimator-comparison.md for detailed trade-offs.
Window Selection
| Goal | Window | Why |
|---|---|---|
| General-purpose PSD | Hann | Good balance, 50% overlap optimal |
| Detect weak tone near strong tone | Blackman-Harris or Kaiser (beta≥10) | Low sidelobes (-92 dB) |
| Resolve two close frequencies | Hann or Kaiser (beta=5) | Narrow main lobe |
| Accurate amplitude measurement | Flat Top | ~0.01 dB scalloping loss |
| Tunable trade-off | Kaiser(N,beta) | Single parameter controls curve |
Key rule: Higher sidelobe suppression costs wider main lobe. Only suppress as much as dynamic range requires. See references/spectral-windows.md for ENBW values and overlap guidelines.
Key Functions
| Function | Purpose |
|---|---|
pspectrum | Power spectrum with automatic defaults; Leakage parameter (0–1) controls resolution vs sidelobe suppression |
periodogram | PSD or power spectrum via single-window DFT |
pwelch | PSD via Welch's averaged periodogram |
pmtm | PSD via Thomson's multitaper method (DPSS/Slepian tapers) |
cpsd | Cross power spectral density |
mscohere | Magnitude-squared coherence (0 to 1) |
pburg / pyulear | AR PSD (Burg / Yule-Walker) |
pmusic / peig | Pseudospectrum (MUSIC / eigenvector) |
rootmusic | Frequency estimation via root-MUSIC |
findpeaks | Locate spectral peaks |
refinepeaks | Sub-bin peak frequency/amplitude refinement (use after findpeaks) |
bandpower | Power in a frequency band |
obw / powerbw | Occupied bandwidth / 3-dB power bandwidth |
meanfreq / medfreq | Mean / median frequency of spectrum |
sfdr | Spurious free dynamic range |
toi | Third-order intercept point (two-tone intermodulation) |
spectralFlatness | Spectral flatness (0=tonal, 1=white noise) |
spectralCrest | Spectral peak-to-mean ratio |
spectralKurtosis | Spectral kurtosis (transient/non-stationarity detection) |
poctave | Fractional-octave spectrum |
plomb | Lomb-Scargle periodogram (non-uniform data) |
spectralEntropy | Spectral entropy (replaces deprecated pentropy) |
spectrumAnalyzer | Live streaming spectrum/spectrogram display (DSP System Toolbox) |
dsp.SpectrumEstimator | Streaming PSD/PS with numeric output (DSP System Toolbox) |
dsp.CrossSpectrumEstimator | Streaming cross-spectrum between two signals (DSP System Toolbox) |
Patterns
Convention reminders (apply to ALL code below):
pow2db(x)for dB — NEVER10*log10(x)detrend(x)only when DC offset or trend is clearly an issue (e.g., large DC spike dominates spectrum)
Single-Sided Amplitude Spectrum
Fs = 1000;
N = length(x);
win = hann(N);
% periodogram with 'power' gives single-sided power per bin
% NFFT=N keeps df=Fs/N ([] defaults to nextpow2 which shifts grid)
[pxx,f] = periodogram(x,win,N,Fs,'power');
ampSpectrum = sqrt(pxx); % power → RMS amplitude
figure
plot(f,ampSpectrum)
xlabel("Frequency (Hz)")
ylabel("Amplitude (RMS)")
title("Single-Sided Amplitude Spectrum")Key points:
Window correction handled automatically by
periodogramFrequency resolution is always
Fs/N— zero-padding only interpolatesFor manual FFT: multiply by
2/Nfor single-sided amplitude, do NOT double DC
PSD with Welch's Method
Fs = 44100;
% x = detrend(x); % uncomment if DC/trend distorts low-frequency estimates
segmentLength = round(Fs * 0.05); % 50 ms → df = 20 Hz
win = hann(segmentLength);
[pxx,f] = pwelch(x,win,round(0.5*segmentLength),[],Fs);
figure
plot(f,pow2db(pxx))
xlabel("Frequency (Hz)")
ylabel("PSD (dB/Hz)")
title("Power Spectral Density (Welch)")
grid onKey points:
Segment length sets resolution:
df = Fs / segmentLengthMore segments = lower variance but coarser resolution (trade-off)
50% overlap with Hann is optimal
Spectral Peak Detection
See references/peak-detection.md for noise-floor-relative thresholds and harmonic detection.
[pxx,f] = pwelch(x,hann(1024),[],[],Fs);
pxxDB = pow2db(pxx);
[peaks,locs] = findpeaks(pxxDB,f, ...
MinPeakHeight=-20, ...
MinPeakDistance=50, ...
MinPeakProminence=10);
figure
plot(f,pxxDB)
hold on
plot(locs,peaks,"rv",MarkerFaceColor="r")
hold off
xlabel("Frequency (Hz)")
ylabel("Power/Frequency (dB/Hz)")
legend("PSD","Peaks")Band Power and Bandwidth
See references/spectral-measurements.md for full details including PSD input, power spectrum + rbw input, and spectral entropy.
Fs = 1000;
pTotal = bandpower(x,Fs,[0 Fs/2]);
pBand = bandpower(x,Fs,[50 150]);
fracPower = pBand / pTotal;
bw = obw(x,Fs); % 99% occupied bandwidth
pbw = powerbw(x,Fs); % 3-dB bandwidth (narrowband/resonance signals only)Fractional-Octave Spectrum (poctave)
See references/poctave-api.md for full syntax, common mistakes, and octave smoothing pattern.
Fs = 44100;
% 1/3-octave with A-weighting (environmental noise)
[p,cf] = poctave(x,Fs,'BandsPerOctave',3,'Weighting','A','FrequencyLimits',[20 20000]);
% From existing PSD (no recomputation needed)
[pxx,f] = pwelch(x,[],[],[],Fs);
[p,cf] = poctave(pxx,Fs,f,'BandsPerOctave',3);Key points:
Use
'BandsPerOctave',3— do NOT use'1/3 octave'(invalid syntax)Only valid types:
'power'(default),'spectrogram'— NO'psd'typeCan accept pre-computed PSD:
poctave(pxx,Fs,f)avoids reprocessingOutput is always power — use
pow2db(p)for dB display
Cross-Spectral Comparison
Fs = 1000;
segLen = 1024;
win = hann(segLen);
[pxy,f] = cpsd(x,y,win,segLen/2,[],Fs);
[cxy,f] = mscohere(x,y,win,segLen/2,[],Fs);
figure
tiledlayout(2,1)
nexttile
plot(f,pow2db(abs(pxy)))
ylabel("|CPSD| (dB)"); xlabel("Frequency (Hz)")
nexttile
plot(f,cxy)
ylabel("Coherence"); xlabel("Frequency (Hz)"); ylim([0 1])Key points:
cpsdis complex — useabsfor magnitude,anglefor phase lagCoherence ≈ 1: linearly related; ≈ 0: unrelated at that frequency
Use same
win/overlapaspwelchfor consistent resolution
Multitaper PSD (Thomson's Method)
Fs = 1000;
nw = 4; % time-halfbandwidth product (default); resolution bandwidth = 2*nw*Fs/N
[pxx,f] = pmtm(x,nw,[],Fs);
plot(f,pow2db(pxx))
xlabel("Frequency (Hz)"); ylabel("PSD (dB/Hz)")Key points:
Uses 2*nw-1 orthogonal DPSS (Slepian) tapers on the full record — no segmentation
Variance reduction without sacrificing frequency resolution (unlike Welch)
Resolution bandwidth =
2*nw*Fs/N— increasenwfor smoother PSD (wider bandwidth), decrease for finer resolutionIdeal for short records where Welch can't segment, or when you need maximum spectral information from limited data
Output is true PSD — directly comparable to
pwelchConfidence intervals available:
[pxx,f,pxxc] = pmtm(x,nw,[],Fs,ConfidenceLevel=0.95)When to prefer over
pwelch: short data, can't afford to segment, or need optimal bias-variance without AR assumptionsWhen to prefer over
pburg: no prior knowledge that signal is AR-like; want a nonparametric estimate
Parametric PSD (Burg Method)
Fs = 1000;
modelOrder = 16; % 2*numPeaks to 4*numPeaks
[pxx,f] = pburg(x,modelOrder,[],Fs);
plot(f,pow2db(pxx))
xlabel("Frequency (Hz)"); ylabel("PSD (dB/Hz)")Key points:
Order too low = over-smoothed; too high = spurious peaks
Burg preferred over Yule-Walker (less biased for short data)
Output is true PSD — comparable to
pwelch
Frequency Estimation with MUSIC
Fs = 1000;
nSinusoids = 2;
p = 2*nSinusoids; % subspace dim: 2 per real sinusoid (pos + neg freq)
[pseudoSpectrum,f] = pmusic(x,p,1024,Fs);
freqEstimates = rootmusic(x,p,Fs); % more accurate than reading peaksKey points:
MUSIC output is a pseudospectrum, NOT a PSD — peak heights ≠ power
p= 2 × number of real sinusoids — usingp = nSinusoidsgives wrong resultsrootmusicgives more accurate frequencies than readingpmusicpeaksWorks best for sinusoids in white noise; short data OK if SNR adequate
Manual FFT-Based PSD (When User Insists)
Only when user explicitly needs manual FFT. See references/manual-fft-psd.md for windowed, power spectrum, and complex-valued variants.
Formula: psdx = (1/(Fs*N)) * abs(fft(x)(1:N/2+1)).^2, double interior bins only (not DC/Nyquist). Windowed: normalize by 1/(Fs*sum(win.^2)).
Conventions
Use
pspectrumas default — redirect manual FFT users to built-in functionsDetrend when warranted — apply
detrend(x)when DC/trend visibly dominates the spectrum or distorts low-frequency estimates; do not blindly detrend every signalLabel axes with units — "Frequency (Hz)", "PSD (dB/Hz)", "Amplitude (V)"
pow2db/db2powfor dB — never10*log10(...)manually. Seereferences/units-and-db.mdfor domain-specific reference levelsFrequency resolution is
Fs/N— zero-padding only interpolatesUse built-in measurement functions —
bandpower,obw,powerbw,findpeaksFavor convenience plots — calling
pwelch(x,[],[],[],Fs),pspectrum(x,Fs),pburg(x,order,[],Fs), etc. without output arguments generates a labeled plot automatically; prefer this over manual plotting when a quick visualization is neededWrite a script — when performing multi-step analysis, write the complete workflow as a
.mscript and run it withrun_matlab_file, rather than executing code piecemeal across multipleevaluate_matlab_codecalls. This produces a reviewable, reproducible artifact
Common Mistakes
| Mistake | Correct Approach |
|---|---|
fft(x) without window | Apply hann(N) or similar |
abs(fft(x)).^2 as "PSD" | Use periodogram/pwelch; if manual, scale by 1/(Fs*N) and double interior only |
| Confusing PSD with power spectrum | PSD = power/Hz; PS = power/bin |
| Zero-padded FFT = higher resolution | Zero-padding interpolates, doesn't resolve |
10*log10(pxx) | Use pow2db |
| Manual integration for band power | Use bandpower(x,Fs,[fLow fHigh]) |
Comparing pspectrum to pwelch directly | Different units (PS vs PSD). See references/pspectrum-equivalence.md |
Using pentropy | Deprecated — use spectralEntropy instead |
pspectrum(...,'TimeResolution',val) for power spectrum | TimeResolution is spectrogram-only. Use 'FrequencyResolution',val or 'Leakage',val |
obw(x,Fs,[],'Percentpower',pct) | obw uses positional args, not name-value. Correct: obw(x,Fs,[fLow fHigh],pct) where pct is the 4th positional arg |
| Filter-bank tone power reads 1–3 dB low | Tone is between bins — filter-bank has narrow pass-bands. Fix: coherent frame length (frameLen = Fs/df) so tones land on bin centers |
snr(x,Fs) unstable for multi-tone with harmonic relationships | snr classifies harmonics specially — 200 Hz = 2nd harmonic of 100 Hz causes inconsistent results. Use per-tone SNR from spectrum instead |
Troubleshooting
See references/troubleshooting.md for detailed explanations and code examples.
"Two tones but only one peak" — Resolution limit (
Fs/N) or sidelobe masking. Fix: more data, lower-sidelobe window (blackmanharris,kaiser(N,15)), or reassigned periodogram ([pxx,f,rpxx,fc] = periodogram(x,win,N,Fs,'reassigned')— 4-output syntax returns reassigned PSD and center-of-energy frequencies for sharper peak localization)."Tone power is wrong" — Scalloping loss (tone between bins). Fix:
flattopwin(N)for amplitude accuracy. Worst case: Hann loses 1.4 dB, Flat Top loses 0.01 dB.
Verification
Verify with Parseval's theorem — total power from spectrum should match time-domain. See references/power-from-spectrum.md for formulas.
pTime = sum(x.^2)/length(x);
pFreq = sum(pxx) * (f(2)-f(1)); % integrate PSD
assert(abs(pTime - pFreq)/pTime < 0.02,"Parseval check failed")Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md21.6 KiB
- manifest.yaml551 B
- references/estimator-comparison.md4.5 KiB
- references/manual-fft-psd.md2.3 KiB
- references/peak-detection.md6.3 KiB
- references/poctave-api.md2.9 KiB
- references/power-from-spectrum.md3.8 KiB
- references/preliminary-analysis.md9.6 KiB
- references/pspectrum-equivalence.md8.3 KiB
- references/spectral-measurements.md9.2 KiB
- references/spectral-windows.md6.6 KiB
- references/streaming-spectral-analysis.md9.0 KiB
- references/troubleshooting.md4.9 KiB
- references/units-and-db.md5.0 KiB
references/pspectrum-equivalence.md
pspectrum vs pwelch/periodogram Equivalence
How to obtain equivalent results between pspectrum and pwelch/periodogram. This is a common user question because pspectrum is convenient but opaque, while pwelch/periodogram give full control.
Key Differences
| Property | pspectrum | pwelch | periodogram |
|---|---|---|---|
| Default output | Power spectrum (PS) | PSD | PSD |
| Can output PS? | Yes (only PS) | Yes ('power' flag) | Yes ('power' flag) |
| Can output PSD? | No | Yes (default) | Yes (default) |
| Units (PS mode) | signal² | signal² | signal² |
| Window | Kaiser (fixed family) | Any | Any |
| Resolution control | FrequencyResolution or Leakage | Segment length | Signal length |
| DC/Nyquist handling | Doubled (known overcompensation) | Not doubled | Not doubled |
| Output points | Fixed (default 4096) | NFFT/2+1 | NFFT/2+1 |
The Fundamental Relationship
Power Spectrum = PSD × RBW
PSD = Power Spectrum / RBWWhere RBW (Resolution Bandwidth) = enbw(window) × Fs / segmentLength
This is the bridge between power spectrum and PSD output from any function.
pspectrum Internal Algorithm (Default Settings)
With default Leakage=0.5:
Window family:
kaiser(nWindow, beta)wherebeta = 40*(1-Leakage)→ default beta=20Target RBW:
max(ENBW/duration, 4*Fs/4095)where ENBW ≈ 2.57 for Kaiser(β=20)First term (
ENBW/duration): the best resolution achievable given the signal lengthSecond term (
4*Fs/4095): ensures at least 4 bins per output point (smoothing floor)pspectrum picks whichever is larger → short signals are resolution-limited, long signals hit the smoothing floor
Window length:
min(N, round(Fs * ENBW / targetRBW))— derived fromRBW = ENBW*Fs/nWindow, solved for nWindowInitial stride:
nWindow / (2*ENBW - 1)— gives ~76% overlap for Kaiser(β=20), maximizing averaging while avoiding redundant computationNumber of segments:
1 + ceil((N - nWindow) / stride)Recomputed stride (when nSegments > 1):
(N - nWindow) / (nSegments - 1)— redistributes stride evenly across all segments (may become fractional internally)Output: 4096 frequency points (single-sided, 0 to Fs/2). This means NFFT = 2×(4096−1) = 8190 (since single-sided output has NFFT/2+1 points → 8190/2+1 = 4096)
One-sided scaling: Multiplies ALL bins by 2 — this overcompensates DC and Nyquist (acknowledged in source code comments)
Frequency reassignment: OFF by default. Only active when
Reassign=true.
Single-segment threshold: For the default 4096 output points and Fs=1000 Hz, pspectrum uses a window of length N-1. For short signals, the "second segment" has negligible data and the result is effectively a single-window periodogram. For longer signals (N > ~2628 at Fs=1000), genuine Welch-like averaging occurs.
Recipe 1: Exact Match for Short Signals
For signals where pspectrum effectively uses a single segment (short signals):
Fs = 1000;
N = length(x);
beta = 20; % default Leakage=0.5
% NFFT=8190 matches pspectrum's 4096 output points: NFFT/2+1 = 4096
[ps,f] = periodogram(x,kaiser(N,beta),8190,Fs,'power');
% Compare
[ps_ref,f_ref] = pspectrum(x,Fs);
% ps ≈ ps_ref on interior bins
% ps_ref(1) = 2*ps(1) at DC (pspectrum overcompensation)
% ps_ref(end) = 2*ps(end) at Nyquist (pspectrum overcompensation)Works perfectly for signals up to ~2628 samples (at Fs=1000).
Recipe 2: Approximate Match for Long Signals
For longer signals where pspectrum performs Welch averaging:
Fs = 1000;
N = length(x);
beta = 20;
% Step 1: Compute pspectrum's internal parameters
estENBW = enbw(kaiser(1000,beta));
duration = (N-1)/Fs;
targetRBW = max(estENBW/duration, 4*Fs/4095);
nWindow = min(N, round(Fs * estENBW / targetRBW));
% Step 2: Compute stride and overlap
stride = nWindow / (2*estENBW - 1);
nSegments = 1 + ceil((N - nWindow)/stride);
if nSegments > 1
stride = (N - nWindow) / (nSegments - 1); % recompute (key step!)
end
ovlp = nWindow - floor(stride);
% Step 3: Compute power spectrum with pwelch
% NFFT=8190 to match pspectrum's 4096 output points (NFFT/2+1 = 4096)
[ps,f] = pwelch(x,kaiser(nWindow,beta),ovlp,8190,Fs,'power');
% Compare to pspectrum
[ps_ref,f_ref] = pspectrum(x,Fs);
% ps matches ps_ref within ~0.2 dB on interior bins
% Remaining difference: pspectrum uses fractional stride (sample-level processing)
% while pwelch requires integer hop sizeWhy not exact for long signals: pspectrum uses multiple parallel estimators with fractional sample offsets (CZT-based, sample-by-sample processing), while pwelch requires integer hop sizes. When the stride is not an integer, rounding introduces small differences (~0.2 dB typical).
Recipe 3: Convert pwelch PSD to Power Spectrum
When you have pwelch PSD output and want to compare with pspectrum:
% pwelch gives PSD by default
[psd,f] = pwelch(x,win,ovlp,[],Fs);
rbw = enbw(win) * Fs / length(win);
ps = psd * rbw; % PSD → Power Spectrum
% Or directly request power spectrum:
[ps,f] = pwelch(x,win,ovlp,[],Fs,'power');Recipe 4: Convert pspectrum to PSD
[ps,f] = pspectrum(x,Fs);
% Compute pspectrum's effective RBW
beta = 20;
estENBW = enbw(kaiser(1000,beta));
duration = (length(x)-1)/Fs;
targetRBW = max(estENBW/duration, 4*Fs/4095);
nWindow = min(length(x), round(Fs*estENBW/targetRBW));
rbw = enbw(kaiser(nWindow,beta)) * Fs / nWindow;
% Convert
psd = ps / rbw;Controlling pspectrum Parameters
| What you want | pspectrum parameter | Effect |
|---|---|---|
| Better frequency resolution | 'FrequencyResolution',value | Longer window → narrower peaks |
| Less spectral leakage | 'Leakage',0.2 (lower) | Higher Kaiser beta → lower sidelobes, wider main lobe |
| More leakage, narrower peaks | 'Leakage',0.8 (higher) | Lower Kaiser beta → higher sidelobes, narrower main lobe |
| More output frequency points | 'FrequencyResolution',small_value | More points, finer grid |
| Frequency reassignment | Reassign=true | Moves energy to true frequency bins (not default) |
Leakage-to-beta mapping: beta = 40 * (1 - Leakage)
| Leakage | Beta | ENBW (bins) | Approximate sidelobe level |
|---|---|---|---|
| 0.0 | 40 | ~4.4 | -100 dB |
| 0.2 | 32 | ~3.6 | -82 dB |
| 0.5 (default) | 20 | ~2.6 | -55 dB |
| 0.8 | 8 | ~1.6 | -32 dB |
| 1.0 | 0 | 1.0 | -13 dB (rectangular) |
Matching Resolution Between Functions
To match pspectrum's resolution with pwelch (or vice versa):
% If you have a pwelch call with segLen and window:
segLen = 1024;
win = hann(segLen);
rbw_welch = enbw(win) * Fs / segLen;
% Set pspectrum to use similar resolution:
[ps,f] = pspectrum(x,Fs,'FrequencyResolution',rbw_welch);
% Note: window shape differs (Kaiser vs Hann) so peak amplitudes
% may vary 1-5% even at matched resolutionCommon Pitfalls
| Mistake | Why it fails | Fix |
|---|---|---|
Comparing pspectrum values directly to pwelch default | Different units (PS vs PSD) | Use pwelch(...,'power') or multiply PSD by RBW |
| Expecting exact match for long signals | Fractional stride vs integer hop | Accept ~0.2 dB tolerance |
Trying pspectrum(x,Fs,'psd') | No PSD output option in pspectrum | Divide output by RBW manually, or use pwelch |
| Ignoring DC/Nyquist difference | pspectrum doubles them (overcompensation) | Skip first/last bin when comparing, or halve them |
| Assuming pspectrum uses Hann/Hamming window | Always Kaiser | Use kaiser(N,20) when matching |
Thinking Reassign is on by default | Off by default | Only set Reassign=true when explicitly needed |
When to Use Which
| Scenario | Recommended |
|---|---|
| Quick exploration, unknown signal | pspectrum — adaptive, good defaults |
| Need exact control of window/overlap/NFFT | pwelch or periodogram |
| Comparing two signals fairly (length-independent) | pwelch (PSD output) |
| Measuring tone amplitude | periodogram(x,win,[],Fs,'power') then sqrt |
| Need both PSD and power spectrum | pwelch with both output modes |
| Publishing results with stated parameters | pwelch — all parameters explicit and reproducible |
| Interactive analysis in Signal Analyzer app | pspectrum — same engine as the app |
Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/signal-processing/matlab-analyze-spectrum · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-analyze-spectrum.zip