## How to plot frequency spectrum of a signal in matlab?

close all;

fs = ;

f = ;

t = /fs/fs;

signal = sin(2*pi*f*t);

plot(t, signal);

title('Time-Domain signal');

fftSignal = fft(signal);

fftSignal = fftshift(fftSignal);

f = fs/2*linspace(-1,1,fs);

figure;

plot(f, abs(fftSignal));

title('magnitude FFT of sine');

xlabel('Frequency (Hz)');

ylabel('magnitude');

noise = 2*randn(size(signal));

figure, plot(t,noise), title('Time-Domain Noise');

fftNoise = fft(noise);

fftNoise = fftshift(fftNoise);

figure, plot(f,abs(fftNoise)), title('Magnitude FFT of noise');

xlabel('Frequency (Hz)');

ylabel('magnitude');

noisySignal = signal + noise;

figure, plot(t,noisySignal), title('Time-Domain Noisy Signal');

fftNoisySignal = fft(noisySignal);

fftNoisySignal = fftshift(fftNoisySignal);

figure, plot(f,abs(fftNoisySignal)), title('Magnitude FFT of noisy signal');

xlabel('Frequency (Hz)');

ylabel('magnitude');

## Select a Web Site

### Estimate the Power Spectrum in MATLAB

The power spectrum (PS) of a time-domain signal is the distribution of power contained within the signal over frequency, based on a finite set of data. The frequency-domain representation of the signal is often easier to analyze than the time-domain representation. Many signal processing applications, such as noise cancellation and system identification, are based on the frequency-specific modifications of signals. The goal of the power spectral estimation is to estimate the power spectrum of a signal from a sequence of time samples. Depending on what is known about the signal, estimation techniques can involve parametric or nonparametric approaches and can be based on time-domain or frequency-domain analysis. For example, a common parametric technique involves fitting the observations to an autoregressive model. A common nonparametric technique is the periodogram. The power spectrum is estimated using Fourier transform methods such as the Welch method and the filter bank method. For signals with relatively small length, the filter bank approach produces a spectral estimate with a higher resolution, a more accurate noise floor, and peaks more precise than the Welch method, with low or no spectral leakage. These advantages come at the expense of increased computation and slower tracking. For more details on these methods, see Spectral Analysis. You can also use other techniques such as the maximum entropy method.

In MATLAB^{®}, you can perform real-time spectral analysis of a dynamic signal using the System object&#x;. You can view the spectral data in the spectrum analyzer and store the data in a workspace variable using the and object functions. Alternately, you can use the System object followed by object to view the spectral data. The output of the object is the spectral data. This data can be acquired for further processing.

### Estimate the Power Spectrum Using dsp.SpectrumAnalyzer

To view the power spectrum of a signal, you can use the System object&#;. You can change the dynamics of the input signal and see the effect those changes have on the power spectrum of the signal in real time.

**Initialization**

Initialize the sine wave source to generate the sine wave and the spectrum analyzer to show the power spectrum of the signal. The input sine wave has two frequencies: one at Hz and the other at Hz. Create two objects, one to generate the Hz sine wave and the other to generate the Hz sine wave.

The spectrum analyzer uses the filter bank approach to compute the power spectrum of the signal.

**Estimation**

Stream in and estimate the power spectrum of the signal. Construct a -loop to run for iterations. In each iteration, stream in samples (one frame) of each sine wave and compute the power spectrum of each frame. To generate the input signal, add the two sine waves. The resultant signal is a sine wave with two frequencies: one at Hz and the other at Hz. Add Gaussian noise with zero mean and a standard deviation of To acquire the spectral data for further processing, use the and the object functions. The variable contains the spectral data that is displayed on the spectrum analyzer along with additional statistics about the spectrum.

In the spectrum analyzer output, you can see two distinct peaks: one at Hz and the other at Hz.

Resolution Bandwidth (RBW) is the minimum frequency bandwidth that can be resolved by the spectrum analyzer. By default, the property of the object is set to . In this mode, RBW is the ratio of the frequency span to In a two-sided spectrum, this value is , while in a one-sided spectrum, it is . The spectrum analyzer in this example shows a one-sided spectrum. Hence, RBW is (/2)/ or Hz

Using this value of , the number of input samples required to compute one spectral update, is given by the following equation: .

In this example, is / or samples.

calculated in the 'Auto' mode gives a good frequency resolution.

To distinguish between two frequencies in the display, the distance between the two frequencies must be at least RBW. In this example, the distance between the two peaks is Hz, which is greater than . Hence, you can see the peaks distinctly. Change the frequency of the second sine wave to Hz. The difference between the two frequencies is less than .

The peaks are not distinguishable.

To increase the frequency resolution, decrease to 1 Hz.

On zooming, the two peaks, which are 15 Hz apart, are now distinguishable.

When you increase the frequency resolution, the time resolution decreases. To maintain a good balance between the frequency resolution and time resolution, change the property to .

During streaming, you can change the input properties or the spectrum analyzer properties and see the effect on the spectrum analyzer output immediately. For example, change the frequency of the second sine wave when the index of the loop is a multiple of

While running the streaming loop, you can see that the peak of the second sine wave changes according to the iteration value. Similarly, you can change any of the spectrum analyzer properties while the simulation is running and see a corresponding change in the output.

### Convert the Power Between Units

The spectrum analyzer provides three units to specify the power spectral density: , , and . Corresponding units of power are , , and . For electrical engineering applications, you can also view the RMS of your signal in or . The default spectrum type is **Power** in .

#### Convert the Power in Watts to dBW and dBm

Power in is given by:

Power in is given by:

For a sine wave signal with an amplitude of 1 V, the power of a one-sided spectrum in is given by:

In this example, this power equals W. Corresponding power in dBm is given by:

Here, the power equals dBm. To confirm this value with a peak finder, click > > .

For a white noise signal, the spectrum is flat for all frequencies. The spectrum analyzer in this example shows a one-sided spectrum in the range [0 Fs/2]. For a white noise signal with a variance of 1e-4, the power per unit bandwidth (P_{unitbandwidth}) is 1e The total power of white noise in **watts** over the entire frequency range is given by:

The number of frequency bins is the ratio of total bandwidth to RBW. For a one-sided spectrum, the total bandwidth is half the sampling rate. RBW in this example is Hz. With these values, the total power of white noise in **watts** is W. In dBm, the power of white noise can be calculated using 10*log10(/10^-3), which equals dBm.

#### Convert Power in Watts to dBFS

If you set the spectral units to and set the full scale () to , power in is computed as:

where:

is the power in watts

For double and float signals,

*Full_Scale*is the maximum value of the input signal.For fixed point or integer signals,

*Full_Scale*is the maximum value that can be represented.

If you specify a manual full scale (set to ), power in is given by:

Where is the full scaling factor specified in the property.

For a sine wave signal with an amplitude of 1 V, the power of a one-sided spectrum in is given by:

In this example, this power equals W and the maximum input signal for a sine wave is 1 V. The corresponding power in dBFS is given by:

Here, the power equals To confirm this value in the spectrum analyzer, run these commands:

#### Convert the Power in dBm to RMS in Vrms

Power in is given by:

Voltage in RMS is given by:

From the previous example, P_{dBm} equals dBm. The V_{rms} is calculated as

which equals

To confirm this value:

Change

**Type**to .Open the peak finder by clicking > > .

### Estimate the Power Spectrum Using dsp.SpectrumEstimator

Alternately, you can compute the power spectrum of the signal using the System object. You can acquire the output of the spectrum estimator and store the data for further processing. To view other objects in the library, type in the MATLAB&#; command prompt, and click .

**Initialization**

Use the same source as in the previous section on using the to estimate the power spectrum. The input sine wave has two frequencies: one at Hz and the other at Hz. Initialize to compute the power spectrum of the signal using the filter bank approach. View the power spectrum of the signal using the object.

**Estimation**

Stream in and estimate the power spectrum of the signal. Construct a -loop to run for iterations. In each iteration, stream in samples (one frame) of each sine wave and compute the power spectrum of each frame. Add Gaussian noise with mean at 0 and a standard deviation of to the input signal.

Using the filter bank approach, the spectral estimate has a high resolution and the peaks are precise with no spectral leakage.

**Convert x-axis to Represent Frequency**

By default, the array plot shows the power spectral data with respect to the number of samples per frame. The number of points on the x-axis equals the length of the input frame. The spectrum analyzer plots the power spectral data with respect to frequency. For a one-sided spectrum, the frequency varies in the range [0 Fs/2]. For a two-sided spectrum, the frequency varies in the range [-Fs/2 Fs/2]. To convert the x-axis of the array plot from sample-based to frequency-based, do the following:

Click on the

**Configuration Properties**icon.For a one-sided spectrum - On

**Main**tab, set**Sample increment**to and**X-offset**to 0.For a two-sided spectrum - On

**Main**tab, set**Sample increment**to and**X-offset**to .

In this example, the spectrum is one-sided and hence, the **Sample increment** and **X-offset** are set to / and 0, respectively. To specify the frequency in kHz, set the **Sample increment** to /

**Live Processing**

The output of the object contains the spectral data and is available for further processing. The data can be processed in real-time or it can be stored in the workspace.

### Related Topics

You have a modified version of this example. Do you want to open this example with your edits?

- Rutgers university programs
- Narrow street 512
- Big twist yarn
- Staff management smx
- Echo starter rope replacement

## Select a Web Site

### Basic Spectral Analysis

The Fourier transform is a tool for performing frequency and power spectrum analysis of time-domain signals.

### Spectral Analysis Quantities

Spectral analysis studies the frequency spectrum contained in discrete, uniformly sampled data. The Fourier transform is a tool that reveals frequency components of a time- or space-based signal by representing it in frequency space. The following table lists common quantities used to characterize and interpret signal properties. To learn more about the Fourier transform, see Fourier Transforms.

Quantity | Description |
---|---|

Sampled data | |

Number of samples | |

Sample frequency (samples per unit time or space) | |

Time or space increment per sample | |

Time or space range for data | |

Discrete Fourier transform of data (DFT) | |

Amplitude of the DFT | |

Power of the DFT | |

Frequency increment | |

Frequency range | |

Nyquist frequency (midpoint of frequency range) |

### Noisy Signal

The Fourier transform can compute the frequency components of a signal that is corrupted by random noise.

Create a signal with component frequencies at 15 Hz and 40 Hz, and inject random Gaussian noise.

The Fourier transform of the signal identifies its frequency components. In MATLAB&#;, the function computes the Fourier transform using a fast Fourier transform algorithm. Use to compute the discrete Fourier transform of the signal.

Plot the power spectrum as a function of frequency. While noise disguises a signal's frequency components in time-based space, the Fourier transform reveals them as spikes in power.

In many applications, it is more convenient to view the power spectrum centered at 0 frequency because it better represents the signal's periodicity. Use the function to perform a circular shift on , and plot the 0-centered power.

### Audio Signal

You can use the Fourier transform to analyze the frequency spectrum of audio data.

The file contains audio data from a Pacific blue whale vocalization recorded by underwater microphones off the coast of California. The file is from the library of animal vocalizations maintained by the Cornell University Bioacoustics Research Program.

Because blue whale calls are so low, they are barely audible to humans. The time scale in the data is compressed by a factor of 10 to raise the pitch and make the call more clearly audible. Read and plot the audio data. You can use the command to listen to the audio.

The first sound is a "trill" followed by three "moans". This example analyzes a single moan. Specify new data that approximately consists of the first moan, and correct the time data to account for the factor-of speed-up. Plot the truncated signal as a function of time.

The Fourier transform of the data identifies frequency components of the audio signal. In some applications that process large amounts of data with , it is common to resize the input so that the number of samples is a power of 2. This can make the transform computation significantly faster, particularly for sample sizes with large prime factors. Specify a new signal length that is a power of 2, and use the function to compute the discrete Fourier transform of the signal. automatically pads the original data with zeros to increase the sample size.

Adjust the frequency range due to the speed-up factor, and compute and plot the power spectrum of the signal. The plot indicates that the moan consists of a fundamental frequency around 17 Hz and a sequence of harmonics, where the second harmonic is emphasized.

### See Also

| | | | |

### Related Topics

## Power Spectral Density Estimates Using FFT

### Even-Length Input with Sample Rate

Obtain the periodogram for an even-length signal sampled at 1 kHz using both and . Compare the results.

Create a signal consisting of a Hz sine wave in *N*(0,1) additive noise. The sampling frequency is 1 kHz. The signal length is samples. Use the default settings of the random number generator for reproducible results.

Obtain the periodogram using . The signal is real-valued and has even length. Because the signal is real-valued, you only need power estimates for the positive or negative frequencies. In order to conserve the total power, multiply all frequencies that occur in both sets &#; the positive and negative frequencies &#; by a factor of 2. Zero frequency (DC) and the Nyquist frequency do not occur twice. Plot the result.

Compute and plot the periodogram using . Show that the two results are identical.

### Input with Normalized Frequency

Use to produce a periodogram for an input using normalized frequency. Create a signal consisting of a sine wave in *N*(0,1) additive noise. The sine wave has an angular frequency of rad/sample. Use the default settings of the random number generator for reproducible results.

Obtain the periodogram using . The signal is real-valued and has even length. Because the signal is real-valued, you only need power estimates for the positive or negative frequencies. In order to conserve the total power, multiply all frequencies that occur in both sets &#; the positive and negative frequencies &#; by a factor of 2. Zero frequency (DC) and the Nyquist frequency do not occur twice. Plot the result.

Compute and plot the periodogram using . Show that the two results are identical.

### Complex-Valued Input with Normalized Frequency

Use to produce a periodogram for a complex-valued input with normalized frequency. The signal is a complex exponential with an angular frequency of rad/sample in complex-valued *N*(0,1) noise. Set the random number generator to the default settings for reproducible results.

Use to obtain the periodogram. Because the input is complex-valued, obtain the periodogram from rad/sample. Plot the result.

Use to obtain and plot the periodogram. Compare the PSD estimates.

### See Also

### Apps

### Functions

Sours: https://www.mathworks.com/help/signal/ug/power-spectral-density-estimates-using-fft.html## Matlab analysis power spectrum

## how can i plot a power spectrum for my signal?

N=;

fs=;

f=1;

ts=1/fs;

t = ts*(0:N-1);

x=sin(2*pi*f*t);

subplot(4,2,1),plot(t,x),title('1hz');

y = fft(x);

N = length(x);

f = (0:N-1)*(fs/N);

pow = abs(y).^2/N;

subplot(4,2,2),plot(f,pow), title('1hz power');

f1=2;

x1=sin(2*pi*f1*t);

subplot(4,2,3),plot(t,x1),title('2hz');

y = fft(x1);

N = length(x);

f = (0:N-1)*(fs/N);

pow = abs(y).^2/N;

subplot(4,2,4),plot(f,pow), title('2hz power');

f2=3;

x2=sin(2*pi*f2*t);

subplot(4,2,5),plot(t,x2),title('3hz');

y = fft(x2);

N = length(x);

f = (0:N-1)*(fs/N);

pow = abs(y).^2/N;

subplot(4,2,6),plot(f,pow), title('3hz power');

x3=x+x1+x2;

subplot(4,2,7),plot(t,x3),title('added freq signal');

y = fft(x3);

N = length(x);

f = (0:N-1)*(fs/N);

pow = abs(y).^2/N;

subplot(4,2,8),plot(f,pow), title('combine hz power');

## Spectral Analysis

Main Content

Power spectrum, coherence, windows

Signal Processing Toolbox&#x; provides a family of spectral analysis functions and apps that let you characterize the frequency content of a signal. FFT-based nonparametric methods, such as Welch’s method or the periodogram, make no assumptions about the input data and can be used with any kind of signal. Parametric and subspace methods, such as Burg’s, covariance, and MUSIC, incorporate prior knowledge of the signal and can yield more accurate spectral estimates.

Compute power spectra of nonuniformly sampled signals or signals with missing samples using the Lomb-Scargle method. Measure signal similarities in the frequency domain by estimating their spectral coherence. Design and analyze Hamming, Kaiser, Gaussian, and other data windows.

- Spectral Estimation

Periodogram, Welch, and Lomb-Scargle PSD, coherence, transfer function, frequency reassignment - Parametric Spectral Estimation

Burg, Yule-Walker, covariance, and modified covariance methods - Subspace Methods

Frequency and pseudospectrum estimates, multiple signal classification (MUSIC), root MUSIC - Windows

Hamming, Blackman, Bartlett, Chebyshev, Taylor, Kaiser

### Featured Examples

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

Select web siteYou can also select a web site from the following list:

### How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

### Similar news:

- Pyside2 theme
- Latin word for rider
- Optimization calculator with constraints
- Thats rough buddy
- Boos cutting board
- Big curly wig
- Play day scoop rockers
- Nevada flag coloring page
- Rahu kalam today bangalore

## pspectrum

Main Content

### Syntax

### Description

example

returns the power spectrum of .

If is a vector or a timetable with a vector of data, then it is treated as a single channel.

If is a matrix, a timetable with a matrix variable, or a timetable with multiple vector variables, then the spectrum is computed independently for each channel and stored in a separate column of .

example

returns the power spectrum of a vector or matrix signal sampled at a rate .

example

returns the power spectrum of a vector or matrix signal sampled at the time instants specified in .

specifies the kind of spectral analysis performed by the function. Specify as , , or . This syntax can include any combination of input arguments from previous syntaxes.

example

specifies additional options using name-value pair arguments. Options include the frequency resolution bandwidth and the percent overlap between adjoining segments.

example

returns the frequencies corresponding to the spectral estimates contained in .

example

also returns a vector of time instants corresponding to the centers of the windowed segments used to compute short-time power spectrum estimates.

also returns a vector of power values corresponding to the estimates contained in a persistence spectrum.

example

with no output arguments plots the spectral estimate in the current figure window. For the plot, the function converts to dB using 10 log_{10}().

### Examples

collapse all

### Power Spectra of Sinusoids

Generate samples of a two-channel complex sinusoid.

The first channel has unit amplitude and a normalized sinusoid frequency of rad/sample

The second channel has an amplitude of and a normalized frequency of rad/sample.

Compute the power spectrum of each channel and plot its absolute value. Zoom in on the frequency range from rad/sample to rad/sample. scales the spectrum so that, if the frequency content of a signal falls exactly within a bin, its amplitude in that bin is the true average power of the signal. For a complex exponential, the average power is the square of the amplitude. Verify by computing the discrete Fourier transform of the signal. For more details, see Measure Power of Deterministic Periodic Signals.

Generate a sinusoidal signal sampled at 1 kHz for milliseconds and embedded in white Gaussian noise. Specify a sinusoid frequency of Hz and a noise variance of ². Store the signal and its time information in a MATLAB&#; timetable.

Compute the power spectrum of the signal. Express the spectrum in decibels and plot it.

Recompute the power spectrum of the sinusoid, but now use a coarser frequency resolution of 25 Hz. Plot the spectrum using the function with no output arguments.

### Two-Sided Spectra

Generate a signal sampled at 3 kHz for 1 second. The signal is a convex quadratic chirp whose frequency increases from Hz to Hz during the measurement. The chirp is embedded in white Gaussian noise.

Compute and plot the two-sided power spectrum of the signal using a rectangular window. For real signals, plots a one-sided spectrum by default. To plot a two-sided spectrum, set to true.

Generate a complex-valued signal with the same duration and sample rate. The signal is a chirp with sinusoidally varying frequency content and embedded in white noise. Compute the spectrogram of the signal and display it as a waterfall plot. For complex-valued signals, the spectrogram is two-sided by default.

### Window Leakage and Tone Resolution

Generate a two-channel signal sampled at Hz for 2 seconds.

The first channel consists of a 20 Hz tone and a 21 Hz tone. Both tones have unit amplitude.

The second channel also has two tones. One tone has unit amplitude and a frequency of 20 Hz. The other tone has an amplitude of 1/ and a frequency of 30 Hz.

Embed the signal in white noise. Specify a signal-to-noise ratio of 40 dB. Plot the signals.

Compute the spectra of the two channels and display them.

The default value for the spectral leakage, , corresponds to a resolution bandwidth of about Hz. The two tones in the first channel are not resolved. The 30 Hz tone in the second channel is visible, despite being much weaker than the other one.

Increase the leakage to , equivalent to a resolution of about Hz. The weak tone in the second channel is clearly visible.

Increase the leakage to the maximum value. The resolution bandwidth is approximately Hz. The two tones in the first channel are resolved. The weak tone in the second channel is masked by the large window sidelobes.

### Persistence Spectrum of Transient Signal

Visualize an interference narrowband signal embedded within a broadband signal.

Generate a chirp sampled at 1 kHz for seconds. The frequency of the chirp increases from Hz to Hz during the measurement.

The signal also contains a Hz sinusoid. The sinusoid has an amplitude of and is present only for 1/6 of the total signal duration.

Compute the spectrogram of the signal. Restrict the frequency range from Hz to Hz. Specify a time resolution of 1 second. Both signal components are visible.

Compute the power spectrum of the signal. The weak sinusoid is obscured by the chirp.

Compute the persistence spectrum of the signal. Now both signal components are clearly visible.

### Spectrogram and Reassigned Spectrogram of Chirp

Generate a quadratic chirp sampled at 1 kHz for 2 seconds. The chirp has an initial frequency of Hz that increases to Hz at *t* = 1 second. Compute the spectrogram using the default settings of the function.

Compute the reassigned spectrogram. Specify a frequency resolution of 10 Hz. Visualize the result using the function with no output arguments.

Recompute the spectrogram using a time resolution of second.

Compute the reassigned spectrogram using the same time resolution.

### Spectrogram of Dial Tone Signal

Create a signal, sampled at 4 kHz, that resembles pressing all the keys of a digital telephone. Save the signal as a MATLAB&#; timetable.

Compute the spectrogram of the signal. Specify a time resolution of second and zero overlap between adjoining segments. Specify the leakage as , which is approximately equivalent to windowing the data with a Hann window.

The spectrogram shows that each key is pressed for half a second, with half-second silent pauses between keys. The first tone has a frequency content concentrated around Hz and Hz, corresponding to the digit in the DTMF standard.

### Input Arguments

collapse all

### &#; Input signal

vector | matrix | timetable

Input signal, specified as a vector, a matrix, or a MATLAB^{®}.

If is a timetable, then it must contain increasing finite row times.

If is a timetable representing a multichannel signal, then it must have either a single variable containing a matrix or multiple variables consisting of vectors.

If is nonuniformly sampled, then interpolates the signal to a uniform grid to compute spectral estimates. The function uses linear interpolation and assumes a sample time equal to the median of the differences between adjacent time points. For a nonuniformly sampled signal to be supported, the median time interval and the mean time interval must obey

**Example: ** is a two-channel signal consisting of sinusoids embedded in white noise.

**Example: ** specifies a two-channel random variable sampled at 1 Hz for 4 seconds.

**Example: ** specifies a two-channel random variable sampled at 1 Hz for 4 seconds.

**Data Types: ** | **Complex Number Support: **Yes

### &#; Sample rate

2*π* (default) | positive numeric scalar

Sample rate, specified as a positive numeric scalar.

### &#; Time values

vector | array | array | scalar

Time values, specified as a vector, a or array, or a scalar representing the time interval between samples.

**Example: ** is a array representing 1 second of sampling at Hz.

**Example: ** is a scalar representing a 1-second time difference between consecutive signal samples.

### &#; Type of spectrum to compute

(default) | |

Type of spectrum to compute, specified as , , or :

&#; Compute the power spectrum of the input. Use this option to analyze the frequency content of a stationary signal. For more information, Spectrum Computation.

&#; Compute the spectrogram of the input. Use this option to analyze how the frequency content of a signal changes over time. For more information, see Spectrogram Computation.

&#; Compute the persistence power spectrum of the input. Use this option to visualize the fraction of time that a particular frequency component is present in a signal. For more information, see Persistence Spectrum Computation.

**Note**

The and options do not support multichannel input.

### Name-Value Arguments

Specify optional comma-separated pairs of arguments. is the argument name and is the corresponding value. must appear inside quotes. You can specify several name and value pair arguments in any order as .

**Example:**windows the data using a rectangular window, computes a reassigned spectrum estimate, and sets all values smaller than &#;35 dB to zero.

### &#; Frequency band limits

(default) | two-element numeric vector

Frequency band limits, specified as the comma-separated pair consisting of and a two-element numeric vector:

If the input contains time information, then the frequency band is expressed in Hz.

If the input does not contain time information, then the frequency band is expressed in normalized units of rad/sample.

By default, computes the spectrum over the whole Nyquist range:

If the specified frequency band contains a region that falls outside the Nyquist range, then truncates the frequency band.

If the specified frequency band lies completely outside of the Nyquist range, then throws an error.

See Spectrum Computation for more information about the Nyquist range.

If is nonuniformly sampled, then linearly interpolates the signal to a uniform grid and defines an effective sample rate equal to the inverse of the median of the differences between adjacent time points. Express in terms of the effective sample rate.

**Example: ** computes the spectrum of a signal with no time information from to rad/sample.

### &#; Frequency resolution bandwidth

real numeric scalar

Frequency resolution bandwidth, specified as the comma-separated pair consisting of and a real numeric scalar, expressed in Hz if the input contains time information, or in normalized units of rad/sample if not. This argument cannot be specified simultaneously with . The default value of this argument depends on the size of the input data. See Spectrogram Computation for details.

**Example: ** computes the spectrum of a signal with no time information with a frequency resolution of / rad/sample.

### &#; Spectral leakage

(default) | real numeric scalar between 0 and 1

Spectral leakage, specified as the comma-separated pair consisting of and a real numeric scalar between 0 and 1. controls the Kaiser window sidelobe attenuation relative to the mainlobe width, compromising between improving resolution and decreasing leakage:

A large leakage value resolves closely spaced tones, but masks nearby weak tones.

A small leakage value finds small tones in the vicinity of larger tones, but smears close frequencies together.

**Example: ** reduces leakage to a minimum at the expense of spectral resolution.

**Example: ** approximates windowing the data with a Hann window.

**Example: ** is equivalent to windowing the data with a rectangular window, maximizing leakage but improving spectral resolution.

### &#; Lower bound for nonzero values

(default) | real scalar

Lower bound for nonzero values, specified as the comma-separated pair consisting of and a real scalar. implements differently based on the value of the argument:

or &#; sets those elements of such that 10 log

_{10}() ≤ to zero. Specify in decibels.&#; sets those elements of smaller than to zero. Specify between 0 and %.

### &#; Number of power bins for persistence spectrum

(default) | integer between 20 and

Number of power bins for persistence spectrum, specified as the comma-separated pair consisting of and an integer between 20 and

### &#; Overlap between adjoining segments

real scalar in the interval [0, )

Overlap between adjoining segments for spectrogram or persistence spectrum, specified as the comma-separated pair consisting of and a real scalar in the interval [0, ). The default value of this argument depends on the spectral window. See Spectrogram Computation for details.

### &#; Reassignment option

(default) |

Reassignment option, specified as the comma-separated pair consisting of and a logical value. If this option is set to , then sharpens the localization of spectral estimates by performing time and frequency reassignment. The reassignment technique produces periodograms and spectrograms that are easier to read and interpret. This technique reassigns each spectral estimate to the center of energy of its bin instead of the bin's geometric center. The technique provides exact localization for chirps and impulses.

### &#; Time resolution of spectrogram or persistence spectrum

real scalar

Time resolution of spectrogram or persistence spectrum, specified as the comma-separated pair consisting of and a real scalar, expressed in seconds if the input contains time information, or as an integer number of samples if not. This argument controls the duration of the segments used to compute the short-time power spectra that form spectrogram or persistence spectrum estimates. cannot be specified simultaneously with . The default value of this argument depends on the size of the input data and, if it was specified, the frequency resolution. See Spectrogram Computation for details.

### &#; Two-sided spectral estimate

false | true

Two-sided spectral estimate, specified as the comma-separated pair consisting of and a logical value.

If this option is , the function computes centered, two-sided spectrum estimates over [&#;

*π*,*π*]. If the input has time information, the estimates are computed over [&#;*f*_{s}/2,*f*_{s}/2], where*f*_{s}is the effective sample rate.If this option is , the function computes one-sided spectrum estimates over the Nyquist range [0,

*π*]. If the input has time information, the estimates are computed over [0,*f*_{s}/2], where*f*_{s}is the effective sample rate. To conserve the total power, the function multiples the power by 2 at all frequencies except 0 and the Nyquist frequency. This option is valid only for real signals.

If not specified, defaults to for real input signals and to for complex input signals.

### Output Arguments

collapse all

### &#; Spectrum

vector | matrix

Spectrum, returned as a vector or a matrix. The type and size of the spectrum depends on the value of the argument:

&#; contains the power spectrum estimate of each channel of . In this case, is of size

*N*_{f}×*N*_{ch}, where*N*_{f}is the length of and*N*_{ch}is the number of channels of . scales the spectrum so that, if the frequency content of a signal falls exactly within a bin, its amplitude in that bin is the true average power of the signal. For example, the average power of a sinusoid is one-half the square of the sinusoid amplitude. For more details, see Measure Power of Deterministic Periodic Signals.&#; contains an estimate of the short-term, time-localized power spectrum of . In this case, is of size

*N*_{f}×*N*_{t}, where*N*_{f}is the length of and*N*_{t}is the length of .&#; contains, expressed as percentages, the probabilities that the signal has components of a given power level at a given time and frequency location. In this case, is of size

*N*_{pwr}×*N*_{f}, where*N*_{pwr}is the length of and*N*_{f}is the length of .

### &#; Spectrum frequencies

vector

Spectrum frequencies, returned as a vector. If the input signal contains time information, then contains frequencies expressed in Hz. If the input signal does not contain time information, then the frequencies are in normalized units of rad/sample.

### &#; Time values of spectrogram

vector | array | array

Time values of spectrogram, returned as a vector of time values in seconds or a array. If the input does not have time information, then contains sample numbers. contains the time values corresponding to the centers of the data segments used to compute short-time power spectrum estimates.

If the input to is a timetable, then has the same format as the time values of the input timetable.

If the input to is a numeric vector sampled at a set of time instants specified by a numeric, , or array, then has the same type and format as the input time values.

If the input to is a numeric vector with a specified time difference between consecutive samples, then is a array.

### &#; Power values of persistence spectrum

vector

Power values of persistence spectrum, returned as a vector.

### More About

collapse all

### Spectrum Computation

To compute signal spectra, finds a compromise between the spectral resolution achievable with the entire length of the signal and the performance limitations that result from computing large FFTs:

If possible, the function computes a single modified periodogram of the whole signal using a Kaiser window.

If it is not possible to compute a single modified periodogram in a reasonable amount of time, the function computes a Welch periodogram: It divides the signal into overlapping segments, windows each segment using a Kaiser window, and averages the periodograms of the segments.

**Spectral Windowing**

Any real-world signal is measurable only for a finite length of time. This fact introduces nonnegligible effects into Fourier analysis, which assumes that signals are either periodic or infinitely long. *Spectral windowing*, which assigns different weights to different signal samples, deals systematically with finite-size effects.

The simplest way to window a signal is to assume that it is identically zero outside of the measurement interval and that all samples are equally significant. This "rectangular window" has discontinuous jumps at both ends that result in spectral ringing. All other spectral windows taper at both ends to lessen this effect by assigning smaller weights to samples close to the signal edges.

The windowing process always involves a compromise between conflicting aims: improving resolution and decreasing leakage:

*Resolution*is the ability to know precisely how the signal energy is distributed in the frequency space. A spectrum analyzer with ideal resolution can distinguish two different tones (pure sinusoids) present in the signal, no matter how close in frequency. Quantitatively, this ability relates to the mainlobe width of the transform of the window.*Leakage*is the fact that, in a finite signal, every frequency component projects energy content throughout the complete frequency span. The amount of leakage in a spectrum can be measured by the ability to detect a weak tone from noise in the presence of a neighboring strong tone. Quantitatively, this ability relates to the sidelobe level of the frequency transform of the window.The spectrum is normalized so that a pure tone within that bandwidth, if perfectly centered, has the correct amplitude.

The better the resolution, the higher the leakage, and vice versa. At one end of the range, a rectangular window has the narrowest possible mainlobe and the highest sidelobes. This window can resolve closely spaced tones if they have similar energy content, but it fails to find the weaker one if they do not. At the other end, a window with high sidelobe suppression has a wide mainlobe in which close frequencies are smeared together.

uses Kaiser windows to carry out windowing. For Kaiser windows, the fraction of the signal energy captured by the mainlobe depends most importantly on an adjustable *shape factor*, *β*. uses shape factors ranging from *β* = 0, which corresponds to a rectangular window, to *β* = 40, where a wide mainlobe captures essentially all the spectral energy representable in double precision. An intermediate value of *β* ≈ 6 approximates a Hann window quite closely. To control *β*, use the name-value pair. If you set to *ℓ*, then *ℓ* and *β* are related by *β* = 40(1 &#; *ℓ*). See for more details.

point Hann window and point Kaiser window with β = in the time domain | point Hann window and point Kaiser window with β = in the frequency domain |

**Parameter and Algorithm Selection**

To compute signal spectra, initially determines the *resolution bandwidth*, which measures how close two tones can be and still be resolved. The resolution bandwidth has a theoretical value of

*t*_{max}&#;*t*_{min}, the*record length*, is the time-domain duration of the selected signal region.ENBW is the

*equivalent noise bandwidth*of the spectral window. See for more details.Use the name-value pair to control the ENBW. The minimum value of the argument corresponds to a Kaiser window with

*β*= The maximum value corresponds to a Kaiser window with*β*= 0.

In practice, however, might lower the resolution. Lowering the resolution makes it possible to compute the spectrum in a reasonable amount of time and to display it with a finite number of pixels. For these practical reasons, the lowest resolution bandwidth can use is

where *f*_{span} is the width of the frequency band specified using . If is not specified, then uses the sample rate as *f*_{span}. RBW_{performance} cannot be adjusted.

To compute the spectrum of a signal, the function chooses the larger of the two values, called the *target resolution bandwidth*:

If the resolution bandwidth is RBW

_{theory}, then computes a single*modified periodogram*for the whole signal. The function uses a Kaiser window with shape factor controlled by the name-value pair. See for more details.If the resolution bandwidth is RBW

_{performance}, then computes a*Welch periodogram*for the signal. The function:Divides the signals into overlapping segments.

Windows each segment separately using a Kaiser window with the specified shape factor.

Averages the periodograms of all the segments.

Welch’s procedure is designed to reduce the variance of the spectrum estimate by averaging different “realizations” of the signals, given by the overlapping sections, and using the window to remove redundant data. See for more details.

The length of each segment (or, equivalently, of the window) is computed using

where

*f*_{Nyquist}is the*Nyquist frequency*. (If there is no aliasing, the Nyquist frequency is one-half the effective sample rate, defined as the inverse of the median of the differences between adjacent time points. The*Nyquist range*is [0,*f*_{Nyquist}] for real signals and [&#;*f*_{Nyquist},*f*_{Nyquist}] for complex signals.)The stride length is found by adjusting an initial estimate,

so that the first window starts exactly on the first sample of the first segment and the last window ends exactly on the last sample of the last segment.

### Spectrogram Computation

To compute the time-dependent spectrum of a nonstationary signal, divides the signal into overlapping segments, windows each segment with a Kaiser window, computes the short-time Fourier transform, and then concatenates the transforms to form a matrix.

A nonstationary signal is a signal whose frequency content changes with time. The *spectrogram* of a nonstationary signal is an estimate of the time evolution of its frequency content. To construct the spectrogram of a nonstationary signal, follows these steps:

Divide the signal into equal-length segments. The segments must be short enough that the frequency content of the signal does not change appreciably within a segment. The segments may or may not overlap.

Window each segment and compute its spectrum to get the

*short-time Fourier transform*.Use the segment spectra to construct the spectrogram:

If called with output arguments, concatenate the spectra to form a matrix.

If called with no output arguments, display the power of each spectrum in decibels segment by segment. Depict the magnitudes side-by-side as an image with magnitude-dependent colormap.

The function can compute the spectrogram only for single-channel signals.

**Divide Signal into Segments**

To construct a spectrogram, first divide the signal into possibly overlapping segments. With the function, you can control the length of the segments and the amount of overlap between adjoining segments using the and name-value pair arguments. If you do not specify the length and overlap, the function chooses a length based on the entire length of the signal and an overlap percentage given by

where ENBW is the *equivalent noise bandwidth* of the spectral window. See and Spectrum Computation for more information.

*Specified Time Resolution*

If the signal does not have time information, specify the time resolution (segment length) in samples. The time resolution must be an integer greater than or equal to 1 and smaller than or equal to the signal length.

If the signal has time information, specify the time resolution in seconds. The function converts the result into a number of samples and rounds it to the nearest integer that is less than or equal to the number but not smaller than 1. The time resolution must be smaller than or equal to the signal duration.

Specify the overlap as a percentage of the segment length. The function converts the result into a number of samples and rounds it to the nearest integer that is less than or equal to the number.

*Default Time Resolution*

If you do not specify a time resolution, then uses the length of the entire signal to choose the length of the segments. The function sets the time resolution as ⌈*N*/*d*⌉ samples, where the ⌈⌉ symbols denote the ceiling function, *N* is the length of the signal, and *d* is a divisor that depends on *N*:

Signal Length (N) | Divisor (d) | Segment Length |
---|---|---|

samples &#; samples | sample &#; samples | |

samples &#; samples | samples &#; samples | |

samples &#; samples | samples &#; samples | |

samples &#; samples | samples &#; samples | |

samples &#; samples | samples &#; samples | |

samples &#; samples | samples &#; samples | |

samples &#; N samples | samples &#; ⌈N / ⌉ samples |

You can still specify the overlap between adjoining segments. Specifying the overlap changes the number of segments. Segments that extend beyond the signal endpoint are zero-padded.

Consider the seven-sample signal . Because ⌈7/2⌉ = ⌈⌉ = 4, the function divides the signal into two segments of length four when there is no overlap. The number of segments changes as the overlap increases.

Number of Overlapping Samples | Resulting Segments |
---|---|

s0 s1 s2 s3 s2 s3 s4 s5 s4 s5 s6 0 | |

s0 s1 s2 s3 s1 s2 s3 s4 s2 s3 s4 s5 s3 s4 s5 s6 |

zero-pads the signal if the last segment extends beyond the signal endpoint. The function returns , a vector of time instants corresponding to the centers of the segments.

**Window the Segments and Compute Spectra**

After divides the signal into overlapping segments, the function windows each segment with a Kaiser window. The shape factor *β* of the window, and therefore the leakage, can be adjusted using the name-value pair. The function then computes the spectrum of each segment and concatenates the spectra to form the spectrogram matrix. To compute the segment spectra, follows the procedure described in Spectrum Computation, except that the lower limit of the resolution bandwidth is

**Display Spectrum Power**

If called with no output arguments, the function displays the power of the short-time Fourier transform in decibels, using a color bar with the default MATLAB colormap. The color bar comprises the full power range of the spectrogram.

### Persistence Spectrum Computation

The *persistence spectrum* of a signal is a time-frequency view that shows the percentage of the time that a given frequency is present in a signal. The persistence spectrum is a histogram in power-frequency space. The longer a particular frequency persists in a signal as the signal evolves, the higher its time percentage and thus the brighter or "hotter" its color in the display. Use the persistence spectrum to identify signals hidden in other signals.

To compute the persistence spectrum, performs these steps:

Compute the spectrogram using the specified leakage, time resolution, and overlap. See Spectrogram Computation for more details.

Partition the power and frequency values into 2-D bins. (Use the name-value pair to specify the number of power bins.)

For each time value, compute a bivariate histogram of the logarithm of the power spectrum. For every power-frequency bin where there is signal energy at that instant, increase the corresponding matrix element by 1. Sum the histograms for all the time values.

Plot the accumulated histogram against the power and the frequency, with the color proportional to the logarithm of the histogram counts expressed as normalized percentages. To represent zero values, use one-half of the smallest possible magnitude.

Power Spectra |

Histograms |

Accumulated Histogram |

### References

[1] harris, fredric j. “On the Use of Windows for Harmonic Analysis with the Discrete Fourier Transform.” *Proceedings of the IEEE ^{®}*. Vol. 66, January , pp. 51&#;

[2] Welch, Peter D. “The Use of Fast Fourier Transform for the Estimation of Power Spectra: A Method Based on Time Averaging Over Short, Modified Periodograms.” *IEEE Transactions on Audio and Electroacoustics*. Vol. 15, June , pp. 70&#;

### Extended Capabilities

### C/C++ Code Generation

Generate C and C++ code using MATLAB&#; Coder&#;.

Usage notes and limitations:

Timetables are not supported for code generation.

### GPU Arrays

Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox&#;.

Usage notes and limitations:

Persistence spectrum is not supported.

Reassigned spectrum or spectrogram is not supported.

For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

### See Also

### Apps

### Functions

**Introduced in Rb**

You have a modified version of this example. Do you want to open this example with your edits?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

Select web siteYou can also select a web site from the following list:

### How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

**652**653 654