MATLAB Examples

Many measurements involve data collected asynchronously by multiple sensors. If you want to integrate the signals, you have to synchronize them. The Signal Processing Toolbox™ has

People predisposed to blood clotting are treated with warfarin, a blood thinner. The international normalized ratio (INR) measures the effect of the drug. Larger doses increase the INR and

Most toolbox functions require you to begin with a vector representing a time base. Consider generating data with a 1000 Hz sample frequency, for example. An appropriate time vector is

Filtering a signal introduces a delay. This means that the output signal is shifted in time with respect to the input.

Consider the weight of a person as recorded (in pounds) during the leap year 2012. The person did not record their weight every day. You would like to study the periodicity of the signal, even

The presence of noise often makes it difficult to determine the spectral content of a signal. Frequency analysis can help in such cases.

Consider the weight of a person as recorded (in pounds) during the leap year 2012. The person did not record their weight every day. You would like to study the periodicity of the signal, but

Design and implement an FIR filter using two command line functions, fir1 and designfilt , and the interactive Filter Designer app.

Measurement uncertainty and noise sometimes make it difficult to spot oscillatory behavior in a signal, even if such behavior is expected.

You can create uniform and nonuniform time vectors for use in computations involving time series.

Sometimes data exhibit unwanted transients, or spikes. Median filtering is a natural way to eliminate them.

It is often difficult to characterize oscillatory behavior in data by looking at time measurements. Spectral analysis can help determine if a signal is periodic and measure the different

Use findpeaks to find values and locations of local maxima in a set of data.

You receive some data and would like to know if it matches a longer stream you have measured. Cross-correlation allows you to make that determination, even when the data are corrupted by

Perform spectral analysis of categorical-valued time-series data. The spectral analysis of categorical-valued time series is useful when you are interested in cyclic behavior of data

You want to differentiate a signal without increasing the noise power. MATLAB®'s function diff amplifies the noise, and the resulting inaccuracy worsens for higher derivatives. To fix

The power of a signal is the sum of the absolute squares of its time-domain samples divided by the signal length, or, equivalently, the square of its RMS level. The function bandpower allows

Spectral coherence helps identify similarity between signals in the frequency domain. Large values indicate frequency components common to the signals.

How sharply does an on/off signal turn on and off? How often and for how long is it activated? Determine all those characteristics for the output of a clock.

Measured signals can show overall patterns that are not intrinsic to the data. These trends can sometimes hinder the data analysis and must be removed.

Alternating current in the United States and several other countries oscillates at a frequency of 60 Hz. Those oscillations often corrupt measurements and have to be subtracted.

Filtering a signal introduces a delay. This means that the output signal is shifted in time with respect to the input. This example shows you how to counteract this effect.

Introduce autocorrelation into a white noise process by filtering. When we introduce autocorrelation into a random signal, we manipulate its frequency content. A moving average filter

Use the cross-correlation sequence to estimate the phase lag between two sine waves. The theoretical cross-correlation sequence of two sine waves at the same frequency also oscillates at

Establish an equivalence between linear and circular convolution.

Find and plot the cross-correlation sequence between two moving average processes. The example compares the sample cross-correlation with the theoretical cross-correlation. Filter an

Create confidence intervals for the autocorrelation sequence of a white noise process. Create a realization of a white noise process with length L=1000 samples. Compute the sample

Use autocorrelation with a confidence interval to analyze the residuals of a least-squares fit to noisy data. The residuals are the differences between the fitted model and the data. In a

Use cross-correlation to align signals. In the most general case, the signals have different lengths, and to synchronize them properly, you must take into account the lengths and the order

Use the cross-correlation sequence to detect the time delay in a noise-corrupted sequence. The output sequence is a delayed version of the input sequence with additive white Gaussian

Many measurements involve data collected asynchronously by multiple sensors. If you want to integrate the signals and study them in tandem, you have to synchronize them. Use xcorr for that

Classify heartbeat electrocardiogram (ECG) data from the PhysioNet 2017 Challenge using deep learning and signal processing. In particular, the example uses Long Short-Term Memory

Design, analyze, and apply a digital filter to your data. It will help you answer questions such as: how do I compensate for the delay introduced by a filter?, How do I avoid distorting my

Use several filter analysis functions in a single figure window by using the Filter Visualization Tool (FVTool), a Graphical User Interface available in the Signal Processing Toolbox™.

Design a Gaussian pulse-shaping FIR filter and the parameters influencing this design. The FIR Gaussian pulse-shaping filter design is done by truncating a sampled version of the

Design a variety of FIR and IIR digital filters with the designfilt function in the Signal Processing Toolbox® product.

The zplane function plots poles and zeros of a linear system. For example, a simple filter with a zero at -1/2 and a complex pole pair at 0.9e^{-j2\pi0.3} and 0.9e^{j2\pi0.3} is

Design FIR and IIR filters based on frequency response specifications using the designfilt function in the Signal Processing Toolbox® product. The example concentrates on lowpass

Devise a simple model of a digital three-way loudspeaker. The system splits the audio input into low-, mid-, and high-frequency bands that correspond respectively to the woofer, the

Generate realistic guitar chords using the Karplus-Strong Algorithm and discrete-time filters.

The impulse response of a digital filter is the output arising from the unit impulse sequence defined as

Use Filter Designer as a convenient alternative to the command line filter design functions.

MATLAB® functions are available to extract the phase response of a filter. Given a frequency response, the function abs returns the magnitude and angle returns the phase angle in radians. To

In the case of FIR filters, it is possible to design linear phase filters that, when applied to data (using filter or conv ), simply delay the output by a fixed number of samples. For IIR filters,

How a GPU can be used to accelerate cross-correlation. Many correlation problems involve large data sets and can be solved much faster using a GPU. To use this example, you must have a Parallel

Analyze a numerically controlled oscillator (NCO) of a digital down-converter (DDC) implemented in fixed-point arithmetic. The example measures the spurious free dynamic range (SFDR)

Use findsignal to find a time-varying signal in your data. It includes examples of how to find exact and closely matching signals by using a distance metric, how to compensate for a slowly

Determine changes or breakouts in signals via cumulative sums and changepoint detection.

Measure signal similarities. It will help you answer questions such as: How do I compare signals with different lengths or different sampling rates? How do I find if there is a signal or just

Use the functions midcross and dtw to extract features from gait signal data. Gait signals are used to study the walking patterns of patients with neurodegenerative disease. The time

Analyze the harmonic distortion of a weakly non-linear system in the presence of noise.

Use the slew rate as an estimate of the rising and falling slopes of a triangular waveform. Create three triangular waveforms. One waveform has rising-falling slopes of \pm2 , one waveform

Generate 2048 samples of a sinusoid of frequency 2.5 kHz sampled at 50 kHz. Add white Gaussian noise such that the signal-to-noise ratio (SNR) is 80 dB.

Estimate the high and low state levels for digital clock data. In contrast to analog voltage signals, signals in digital circuits have only two states: HIGH and LOW. Information is conveyed

Create a rectangular pulse waveform and measure its duty cycle. You can think of a rectangular pulse waveform as a sequence of on and off states. One pulse period is the total duration of an on

Perform basic peak analysis. It will help you answer questions such as: How do I find peaks in my signal? How do I measure distance between peaks? How do I measure the amplitude of peaks of a

Find the root mean square (RMS) value of a sine wave, a square wave, and a rectangular pulse train using rms . The waveforms in this example are discrete-time versions of their continuous-time

Shows how to measure the total harmonic distortion (THD) of a sinusoidal signal. The example uses the following scenario: A manufacturer of audio speakers claims the model A speaker

Analyze pulses and transitions and compute metrics including rise time, fall time, slew rate, overshoot, undershoot, pulse width, and duty cycle.

Create a signal that consists of a sum of bell curves. Specify the location, height, and width of each curve.

Avoid aliasing when downsampling a signal. If a discrete-time signal's baseband spectral support is not limited to an interval of width radians, downsampling by results in aliasing.

Use downsample to obtain the phases of a signal. Downsampling a signal by M can produce M unique phases. For example, if you have a discrete-time signal, x, with x(0) x(1) x(2) x(3), ..., the M

Upsample a signal and apply a lowpass interpolation filter with interp . Upsampling by L inserts L - 1 zeros between every element of the original signal. Upsampling can create imaging

Use moving average filters and resampling to isolate the effect of periodic components of the time of day on hourly temperature readings, as well as remove unwanted line noise from an

Change the sample rate of a signal. The example has two parts. Part one changes the sample rate of a sinusoidal input from 44.1 kHz to 48 kHz. This workflow is common in audio processing. The

Filter before downsampling to mitigate the distortion caused by aliasing. You can use decimate or resample to filter and downsample with one function. Alternatively, you can lowpass

Several ways to simulate the output of a sample-and-hold system by upsampling and filtering a signal.

Generate widely used periodic and aperiodic waveforms, sequences (impulse, step, ramp), multichannel signals, pulse trains, sinc and Dirichlet functions available in the Signal

The toolbox also provides functions for generating several widely used aperiodic waveforms:

Resample nonuniformly sampled signals to a new uniform rate. It shows how to apply a custom filter on irregularly sampled data to reduce aliasing. It also shows how to use detrending to remove

The toolbox provides functions for generating widely used periodic waveforms:

Since MATLAB® is a programming language, an endless variety of different signals is possible. Here are some statements that generate a unit impulse, a unit step, a unit ramp, and a unit

The pulstran function generates pulse trains from either continuous or sampled prototype pulses. The following example generates a pulse train consisting of the sum of multiple delayed

The function diric computes the Dirichlet function, sometimes called the periodic sinc or aliased sinc function, for an input vector or matrix x . The Dirichlet function is defined by

The sinc function computes the mathematical sinc function for an input vector or matrix x . Viewed as a function of time, or space, the sinc function is the inverse Fourier transform of the

Reconstruct missing data via interpolation, anti-aliasing filtering, and autoregressive modeling.

A naive implementation of the procedure used by hampel to detect and remove outliers. The actual function is much faster.

Upsample a signal and how upsampling can result in images. Upsampling a signal contracts the spectrum. For example, upsampling a signal by 2 results in a contraction of the spectrum by a

Resample a uniformly sampled signal to a new uniform rate. It shows how to reduce the impact of large transients as well as how to remove unwanted high frequency content.

Load a file that contains measurements of the international normalized ratio (INR) performed on a patient over a five-year period. The INR measures the effect of warfarin, a blood thinner

Create a signal, sampled at 4 kHz, that resembles dialing all the keys of a digital telephone. Save the signal as a MATLAB® timetable.

Assess the order of an autoregressive model using the partial autocorrelation sequence. For these processes, you can use the partial autocorrelation sequence to help with model order

Compare the relationship between autoregressive modeling and linear prediction. Linear prediction and autoregressive modeling are two different problems that can yield the same

Estimate vowel formant frequencies using linear predictive coding (LPC). The formant frequencies are obtained by finding the roots of the prediction polynomial.

Obtain the prediction polynomial from an autocorrelation sequence. The example also shows that the resulting prediction polynomial has an inverse that produces a stable all-pole filter.

Perform and interpret basic frequency-domain signal analysis. The example discusses the advantages of using frequency-domain versus time-domain representations of a signal and

Create a signal consisting of three noisy sinusoids and a chirp, sampled at 200 kHz for 0.1 second. The frequencies of the sinusoids are 1 kHz, 10 kHz, and 20 kHz. The sinusoids have different

Resolve closely spaced sine waves using subspace methods. Subspace methods assume a harmonic model consisting of a sum of sine waves, possibly complex, in additive noise. In a

In general terms, one way of estimating the PSD of a process is to simply find the discrete-time Fourier transform of the samples of the process (usually done on a grid with an FFT) and

Use the discrete Fourier transform to construct a linear regression model for a time series. The time series used in this example is the monthly number of accidental deaths in the United

Obtain nonparametric power spectral density (PSD) estimates equivalent to the periodogram using fft . The examples show you how to properly scale the output of fft for even-length inputs,

Reduce bias and variability in the periodogram. Using a window can reduce the bias in the periodogram, and using windows with averaging can reduce variability.

The modified periodogram windows the time-domain signal prior to computing the DFT in order to smooth the edges of the signal. This has the effect of reducing the height of the sidelobes or

An improved estimator of the PSD is the one proposed by Welch. The method consists of dividing the time series data into (possibly overlapping) segments, computing a modified periodogram of

The following sections discuss the performance of the periodogram with regard to the issues of leakage, resolution, bias, and variance.

One application of Welch's method is nonparametric system identification. Assume that H is a linear, time invariant system, and x ( n ) and y ( n ) are the input to and output of H , respectively.

Use the cross spectrum to obtain the phase lag between sinusoidal components in a bivariate time series. The example also uses the magnitude-squared coherence to identify significant

Measure the power of deterministic periodic signals. Although continuous in time, periodic deterministic signals produce discrete power spectra.

Use zero padding to obtain an accurate estimate of the amplitude of a sinusoidal signal. Frequencies in the discrete Fourier transform (DFT) are spaced at intervals of F_s/N , where F_s is the

Generate 1024 samples of a chirp sampled at 1024 kHz. The chirp has an initial frequency of 50 kHz and reaches 100 kHz at the end of the sampling. Add white Gaussian noise such that the

Perform and interpret basic time-frequency signal analysis. In practical applications, many signals are nonstationary. This means that their frequency-domain representation (their

The periodogram can be interpreted as filtering a length L signal, x_L(n) , through a filter bank (a set of filters in parallel) of L FIR bandpass filters. The 3 dB bandwidth of each of these

The magnitude-squared coherence between two signals x ( n ) and y ( n ) is

Perform spectral analysis on nonuniformly sampled signals. It helps you determine if a signal is uniformly sampled or not, and if not, it shows how to compute its spectrum or its power

Assess the significance of a sinusoidal component in white noise using Fisher's g -statistic. Fisher's g -statistic is the ratio of the largest periodogram value to the sum of all the

There are two design formulas that can help you design FIR filters to meet a set of filter specifications using a Kaiser window. To achieve a sidelobe height of – α dB, the β ( beta ) parameter is

Load a file that contains audio data from a Pacific blue whale, sampled at 4 kHz. The file is from the library of animal vocalizations maintained by the Cornell University Bioacoustics

The Chebyshev window minimizes the mainlobe width, given a particular sidelobe height. It is characterized by an equiripple behavior. Its sidelobes all have the same height.

Consider a sinusoid, f(x)=e^{j2\pi\nu x} , windowed with a Gaussian window, g(t)=e^{-\pi t^2} . The short-time transform is

The Signal Processing Toolbox™ product provides functions that return the time-dependent Fourier transform for a sequence, or displays this information as a spectrogram. The

Visualize an interference narrowband signal embedded within a broadband signal.

Compute the instantaneous frequency of a signal using the Fourier synchrosqueezed transform.

Compress a speech signal using the discrete cosine transform (DCT).

Use the Goertzel function to implement a DFT-based DTMF detection algorithm.

Determine the analytic signal. The example also demonstrates that the imaginary part of the analytic signal corresponding to a cosine is a sine with the same frequency. If the cosine has a

Extract the envelope of a signal.

Estimate a speaker's fundamental frequency using the complex cepstrum. The example also estimates the fundamental frequency using a zero-crossing method and compares the results.

Cepstrum analysis is a nonlinear signal processing technique with a variety of applications in areas such as speech and image processing.

The Hilbert transform facilitates the formation of the analytic signal. The analytic signal is useful in the area of communications, particularly in bandpass signal processing. The

The discrete cosine transform (DCT) is closely related to the discrete Fourier transform (DFT). The DFT is actually one step in the computation of the DCT for a sequence. The DCT, however, has

Use the Hilbert transform to carry out single-sideband (SSB) amplitude modulation (AM) of a signal. Single-sideband AM signals have less bandwidth than normal AM signals.

Use the discrete Hilbert Transform to implement Single Sideband Modulation.

Use the Walsh-Hadamard transform (WHT) and some of its properties by showcasing two applications: communications using spread spectrum and processing of ECG signals.

The Hilbert transform estimates the instantaneous frequency of a signal for monocomponent signals only. A monocomponent signal is described in the time-frequency plane by a single

The discrete Fourier transform, or DFT, is the primary tool of digital signal processing. The foundation of the product is the fast Fourier transform (FFT), a method for computing the DFT

The chirp Z-transform (CZT) is useful in evaluating the Z-transform along contours other than the unit circle. The chirp Z-transform is also more efficient than the DFT algorithm for the

Analyze a vibration signal using order analysis. Order analysis is used to quantify noise or vibration in rotating machinery whose rotational speed changes over time. An order refers to a

Generate a signal that consists of two linear chirps and a quadratic chirp, all sampled at 600 Hz for 5 seconds. The system that produces the signal increases its rotational speed from 10 to 40

Identify state-space models of systems. Use the models to compute frequency-response functions and modal parameters. This example requires a System Identification Toolbox™ license.

Estimate frequency-response functions (FRFs) and modal parameters from experimental data. The first section describes a simulated experiment that excites a three-degree-of-freedom

Analyze vibration signals from a gearbox using time-synchronous averaging and envelope spectra. These functions are especially useful in the predictive maintenance of gearboxes, which

Match bin range to data range.

The xcorr3 function gives a map of correlation between grid cells of a 3D spatiotemporal dataset and a reference time series.

The Evolutionary Power Spectral Density (EPSD) [1] is compared to the well-known spectrogram implemented in Matlab. The EPSD produces a smoother signal, especially if the amount of data

Scatter plot array of environmental data

Use coplot

Scatter plot with color.

Use scatter3

Filled contour of galaxy data with consistent colorbar

This example was authored by the MathWorks community.

Use labels instead of legend.

Remove average seasonal effect using seasonaloess.

Qqplot for singer

Use scattermatrixc

Use slplot.

Use normalqqplot in subplot array.

Show classic and robust fits.

Use rdplot.

The filter1 function performs frequency or wavelength filtering on a 1D array using zero-phase Butterworth filtering.

Use slplotr after log transform.

Use boxparams, boxplotter

Use jitter

Quantileplot for singer

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: .

You can also select a web site from the following list:

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