spectrogram — Compute a short-time Fourier transform spectrogram.
spectrogram(x) computes a short-time Fourier transform (STFT) of a signal. Optional arguments select the segment window, overlap, DFT length or explicit frequency grid, sampling frequency, frequency range, and PSD or power-spectrum scaling.
Syntax
s = spectrogram(x, win, nOverlap, freqSpec, Fs, freqRange, spectrumType)
[s, f, t, ps, fc, tc] = spectrogram(x, win, nOverlap, freqSpec, Fs, freqRange, spectrumType)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
x | NumericArray | Yes | — | Input signal vector. |
win | Any | No | [] | Hamming-window length, window vector, or [] for the default window. |
nOverlap | NumericScalar | No | [] | Number of overlapped samples between adjacent segments. |
freqSpec | NumericArray | No | [] | DFT length or explicit frequency vector. |
Fs | NumericScalar | No | — | Sampling frequency in Hz. |
freqRange | StringScalar | No | — | Frequency range selector: `onesided`, `twosided`, or `centered`. |
spectrumType | StringScalar | No | psd | Spectral estimate scaling: `psd` or `power`. |
Returns
| Name | Type | Description |
|---|---|---|
s | NumericArray | Complex short-time Fourier transform matrix. |
f | NumericArray | Frequencies in radians/sample or Hz when fs is supplied. |
t | NumericArray | Segment midpoint sample indices or time instants when fs is supplied. |
ps | NumericArray | Power spectral density or power spectrum estimate for each segment. |
fc | NumericArray | Center frequency matrix for reassigned-output compatibility. |
tc | NumericArray | Center time matrix for reassigned-output compatibility. |
Returned values from spectrogram depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:spectrogram:ArgCount | The argument count is outside supported forms. | spectrogram: expected spectrogram(x, [win, [nOverlap, [freqSpec, [Fs, [freqRange_or_spectrumType]]]]]) |
RunMat:spectrogram:InvalidSignal | Input signal is not a numeric vector. | spectrogram: x must be a nonempty numeric vector |
RunMat:spectrogram:InvalidWindow | Window input is invalid. | spectrogram: win must be [] or a nonempty finite real vector or positive integer length |
RunMat:spectrogram:InvalidOverlap | Overlap is invalid. | spectrogram: nOverlap must be a nonnegative integer smaller than the window length |
RunMat:spectrogram:InvalidFreqSpec | Frequency specification is invalid. | spectrogram: freqSpec must be a positive integer or finite real frequency vector with at least two elements |
RunMat:spectrogram:InvalidFs | Sampling frequency is invalid. | spectrogram: Fs must be a positive finite scalar |
RunMat:spectrogram:InvalidOption | Frequency range, spectrum type, or display option is invalid. | spectrogram: expected 'onesided', 'twosided', 'centered', 'psd', 'power', 'reassigned', or 'yaxis' |
RunMat:spectrogram:Internal | Output tensor construction fails internally. | spectrogram: internal error |
How spectrogram works
s = spectrogram(x)returns the complex STFT matrix with time increasing across columns and frequency increasing down rows.[s, f, t, ps] = spectrogram(...)also returns the frequency vector, segment midpoint vector, and PSD or power-spectrum matrix.winmay be a positive scalar length, a finite real window vector, or[].[]uses a Hamming window sized to divide the signal into about eight 50%-overlapped sections.nOverlapdefaults to half the window length and must be less than the window length.freqSpecdefaults tomax(256, 2^nextpow2(length(win))). A real frequency vector with at least two elements may be supplied to evaluate explicit frequencies.- Omitting
Fsuses normalized radians/sample and segment midpoint times divided by2*pi. PassingFsas[]uses a 1 Hz sample rate. - Real inputs default to one-sided output; complex inputs default to two-sided output and reject
'onesided'. - The optional range selector accepts
'onesided','twosided', or'centered'. Range selectors are not combined with explicit frequency vectors. - The optional spectrum type accepts
'psd'(default) or'power';'power'uses coherent-gain normalization. 'yaxis'is accepted as a plotting-orientation no-op for numeric execution.'reassigned'is rejected until true energy-center reassignment is implemented.
Examples
STFT of a sine wave
fs = 1000;
t = (0:999) / fs;
x = sin(2*pi*100*t);
[s, f, tt, ps] = spectrogram(x, hamming(128), 64, 256, fs);Use scalar window length
[s, f, t] = spectrogram(randn(1,1024), 128, 64, 256);Centered complex STFT
x = exp(1i*2*pi*(0:127)/16);
[s, f, t] = spectrogram(x, 32, 16, 64, 'centered');Power spectrum scaling
[s, f, t, p] = spectrogram(randn(1,512), 64, 32, 128, 'power');Explicit normalized frequencies
w = linspace(0, pi, 64);
[s, wout, t] = spectrogram(randn(1,512), hamming(128), 64, w);Using spectrogram with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how spectrogram changes the result.
Run a small spectrogram example, explain the result, then change one input and compare the output.
FAQ
What is the relationship between s and ps?⌄
s is the complex STFT. ps is derived from abs(s).^2 using PSD or power-spectrum normalization and one-sided doubling when appropriate.
Does spectrogram plot when no outputs are requested?⌄
RunMat currently returns values using normal output-count semantics instead of opening a plot. The 'yaxis' token is accepted so scripts can continue numeric execution.
Does RunMat implement reassigned spectrogram energy centers?⌄
No. RunMat rejects 'reassigned' rather than returning unreassigned coordinate grids.
Related Math functions
Signal
blackman · butter · buttord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · sawtooth · sinc · square · tripuls · unwrap · upsample · zplane
Elementwise
abs · angle · complex · conj · double · exp · expm1 · factorial · gamma · heaviside · hypot · imag · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · sign · single · sqrt · times
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · atanh · cos · cosd · cosh · deg2rad · rad2deg · sin · sind · sinh · tan · tand · tanh
Reduction
all · any · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · mean · median · min · nnz · prod · std · sum · trapz · var
Structure
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how spectrogram is executed, line by line, in Rust.
- View the source for spectrogram in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.