Magnitude-squared coherence - MATLAB mscohere (2024)

Magnitude-squared coherence

collapse all in page

Syntax

cxy = mscohere(x,y)

cxy = mscohere(x,y,window)

cxy = mscohere(x,y,window,noverlap)

cxy = mscohere(x,y,window,noverlap,nfft)

cxy = mscohere(___,'mimo')

[cxy,w] = mscohere(___)

[cxy,f] = mscohere(___,fs)

[cxy,w] = mscohere(x,y,window,noverlap,w)

[cxy,f] = mscohere(x,y,window,noverlap,f,fs)

[___] = mscohere(x,y,___,freqrange)

mscohere(___)

Description

cxy = mscohere(x,y) findsthe magnitude-squared coherence estimate, cxy,of the input signals, x and y.

  • If x and y areboth vectors, they must have the same length.

  • If one of the signals is a matrix and the other isa vector, then the length of the vector must equal the number of rowsin the matrix. The function expands the vector and returns a matrixof column-by-column magnitude-squared coherence estimates.

  • If x and y arematrices with the same number of rows but different numbers of columns,then mscohere returns a multiple coherence matrix.The mth column of cxy containsan estimate of the degree of correlation between all the input signalsand the mth output signal. See Magnitude-Squared Coherence for more information.

  • If x and y arematrices of equal size, then mscohere operatescolumn-wise: cxy(:,n) = mscohere(x(:,n),y(:,n)).To obtain a multiple coherence matrix, append 'mimo' tothe argument list.

cxy = mscohere(x,y,window) uses window todivide x and y into segmentsand perform windowing. You must use at least two segments. Otherwise,the magnitude-squared coherence is 1 for all frequencies. In the MIMOcase, the number of segments must be greater than the number of inputchannels.

cxy = mscohere(x,y,window,noverlap) uses noverlap samplesof overlap between adjoining segments.

example

cxy = mscohere(x,y,window,noverlap,nfft) uses nfft samplingpoints to calculate the discrete Fourier transform.

example

cxy = mscohere(___,'mimo') computesa multiple coherence matrix for matrix inputs. This syntax can includeany combination of input arguments from previous syntaxes.

[cxy,w] = mscohere(___) returnsa vector of normalized frequencies, w, at whichthe magnitude-squared coherence is estimated.

example

[cxy,f] = mscohere(___,fs) returnsa vector of frequencies, f, expressed in termsof the sample rate, fs, at which the magnitude-squaredcoherence is estimated. fs must be the sixthnumeric input to mscohere. To input a samplerate and still use the default values of the preceding optional arguments,specify these arguments as empty, [].

[cxy,w] = mscohere(x,y,window,noverlap,w) returnsthe magnitude-squared coherence estimate at the normalized frequenciesspecified in w.

[cxy,f] = mscohere(x,y,window,noverlap,f,fs) returnsthe magnitude-squared coherence estimate at the frequencies specifiedin f.

[___] = mscohere(x,y,___,freqrange) returnsthe magnitude-squared coherence estimate over the frequency rangespecified by freqrange. Valid options for freqrange are 'onesided', 'twosided',and 'centered'.

example

mscohere(___) withno output arguments plots the magnitude-squared coherence estimatein the current figure window.

Examples

collapse all

Coherence Estimate of Two Sequences

Open Live Script

Compute and plot the coherence estimate between two colored noise sequences.

Generate a signal consisting of white Gaussian noise.

r = randn(16384,1);

To create the first sequence, bandpass filter the signal. Design a 16th-order filter that passes normalized frequencies between 0.2π and 0.4π rad/sample. Specify a stopband attenuation of 60 dB. Filter the original signal.

dx = designfilt('bandpassiir','FilterOrder',16, ... 'StopbandFrequency1',0.2,'StopbandFrequency2',0.4, ... 'StopbandAttenuation',60);x = filter(dx,r);

To create the second sequence, design a 16th-order filter that stops normalized frequencies between 0.6π and 0.8π rad/sample. Specify a passband ripple of 0.1 dB. Filter the original signal.

dy = designfilt('bandstopiir','FilterOrder',16, ... 'PassbandFrequency1',0.6,'PassbandFrequency2',0.8, ... 'PassbandRipple',0.1);y = filter(dy,r);

Estimate the magnitude-squared coherence of x and y. Use a 512-sample Hamming window. Specify 500 samples of overlap between adjoining segments and 2048 DFT points.

[cxy,fc] = mscohere(x,y,hamming(512),500,2048);

Plot the coherence function and overlay the frequency responses of the filters.

[qx,f] = freqz(dx);qy = freqz(dy);plot(fc/pi,cxy)hold onplot(f/pi,abs(qx),f/pi,abs(qy))hold off

Magnitude-squared coherence - MATLAB mscohere (1)

Multiple Coherence and Ordinary Coherence

Open Live Script

Generate a random two-channel signal, x. Generate another signal, y, by lowpass filtering the two channels and adding them together. Specify a 30th-order FIR filter with a cutoff frequency of 0.3π and designed using a rectangular window.

h = fir1(30,0.3,rectwin(31));x = randn(16384,2);y = sum(filter(h,1,x),2);

Compute the multiple-coherence estimate of x and y. Window the signals with a 1024-sample Hann window. Specify 512 samples of overlap between adjoining segments and 1024 DFT points. Plot the estimate.

noverlap = 512;nfft = 1024;mscohere(x,y,hann(nfft),noverlap,nfft,'mimo')

Magnitude-squared coherence - MATLAB mscohere (2)

Compare the coherence estimate to the frequency response of the filter. The drops in coherence correspond to the zeros of the frequency response.

[H,f] = freqz(h);hold onyyaxis rightplot(f/pi,20*log10(abs(H)))hold off

Magnitude-squared coherence - MATLAB mscohere (3)

Compute and plot the ordinary magnitude-squared coherence estimate of x and y. The estimate does not reach 1 for any of the channels.

figuremscohere(x,y,hann(nfft),noverlap,nfft)

Magnitude-squared coherence - MATLAB mscohere (4)

Coherence of MIMO System

Open Live Script

Generate two multichannel signals, each sampled at 1 kHz for 2 seconds. The first signal, the input, consists of three sinusoids with frequencies of 120 Hz, 360 Hz, and 480 Hz. The second signal, the output, is composed of two sinusoids with frequencies of 120 Hz and 360 Hz. One of the sinusoids lags the first signal by π/2. The other sinusoid has a lag of π/4. Both signals are embedded in white Gaussian noise.

fs = 1000;f = 120;t = (0:1/fs:2-1/fs)';inpt = sin(2*pi*f*[1 3 4].*t);inpt = inpt+randn(size(inpt));oupt = sin(2*pi*f*[1 3].*t-[pi/2 pi/4]);oupt = oupt+randn(size(oupt));

Estimate the degree of correlation between all the input signals and each of the output channels. Use a Hamming window of length 100 to window the data. mscohere returns one coherence function for each output channel. The coherence functions reach maxima at the frequencies shared by the input and the output.

[Cxy,f] = mscohere(inpt,oupt,hamming(100),[],[],fs,'mimo');for k = 1:size(oupt,2) subplot(size(oupt,2),1,k) plot(f,Cxy(:,k)) title(['Output ' int2str(k) ', All Inputs'])end

Magnitude-squared coherence - MATLAB mscohere (5)

Switch the input and output signals and compute the multiple coherence function. Use the same Hamming window. There is no correlation between input and output at 480 Hz. Thus there are no peaks in the third correlation function.

[Cxy,f] = mscohere(oupt,inpt,hamming(100),[],[],fs,'mimo');for k = 1:size(inpt,2) subplot(size(inpt,2),1,k) plot(f,Cxy(:,k)) title(['Input ' int2str(k) ', All Outputs'])end

Magnitude-squared coherence - MATLAB mscohere (6)

Repeat the computation, using the plotting functionality of mscohere.

clfmscohere(oupt,inpt,hamming(100),[],[],fs,'mimo')

Magnitude-squared coherence - MATLAB mscohere (7)

Compute the ordinary coherence function of the second signal and the first two channels of the first signal. The off-peak values differ from the multiple coherence function.

[Cxy,f] = mscohere(oupt,inpt(:,[1 2]),hamming(100),[],[],fs);plot(f,Cxy)

Magnitude-squared coherence - MATLAB mscohere (8)

Find the phase differences by computing the angle of the cross-spectrum at the points of maximum coherence.

Pxy = cpsd(oupt,inpt(:,[1 2]),hamming(100),[],[],fs);[~,mxx] = max(Cxy);for k = 1:2 fprintf('Phase lag %d = %5.2f*pi\n',k,angle(Pxy(mxx(k),k))/pi)end
Phase lag 1 = -0.51*piPhase lag 2 = -0.22*pi

Modify Magnitude-Squared Coherence Plot

Open Live Script

Generate two sinusoidal signals sampled for 1second each at 1kHz. Each sinusoid has a frequency of 250Hz. One of the signals lags the other in phase by π/3radians. Embed both signals in white Gaussian noise of unit variance.

fs = 1000;f = 250;t = 0:1/fs:1-1/fs;um = sin(2*pi*f*t)+rand(size(t));un = sin(2*pi*f*t-pi/3)+rand(size(t));

Use mscohere to compute and plot the magnitude-squared coherence of the signals.

mscohere(um,un,[],[],[],fs)

Magnitude-squared coherence - MATLAB mscohere (9)

Modify the title of the plot, the label of the x-axis, and the limits of the y-axis.

title('Magnitude-Squared Coherence')xlabel('f (Hz)')ylim([0 1.1])

Magnitude-squared coherence - MATLAB mscohere (10)

Use gca to obtain a handle to the current axes. Change the locations of the tick marks. Remove the label of the y-axis.

ax = gca;ax.XTick = 0:250:500;ax.YTick = 0:0.25:1;ax.YLabel.String = [];

Magnitude-squared coherence - MATLAB mscohere (11)

Call the Children property of the handle to change the color and width of the plotted line.

ln = ax.Children;ln.Color = [0.8 0 0];ln.LineWidth = 1.5;

Magnitude-squared coherence - MATLAB mscohere (12)

Alternatively, use set and get to modify the line properties.

set(get(gca,'Children'),'Color',[0 0.4 0],'LineStyle','--','LineWidth',1)

Magnitude-squared coherence - MATLAB mscohere (13)

Input Arguments

collapse all

x, yInput signals
vectors | matrices

Input signals, specified as vectors or matrices.

Example: cos(pi/4*(0:159))+randn(1,160) specifiesa sinusoid embedded in white Gaussian noise.

Data Types: single | double
Complex Number Support: Yes

windowWindow
integer | vector | []

Window, specified as an integer or as a row or column vector.Use window to divide the signal into segments:

  • If window is an integer, then mscohere divides x and y intosegments of length window and windows each segmentwith a Hamming window of that length.

  • If window is a vector, then mscohere divides x and y intosegments of the same length as the vector and windows each segmentusing window.

If the length of x and y cannotbe divided exactly into an integer number of segments with noverlap overlappingsamples, then the signals are truncated accordingly.

If you specify window as empty, then mscohere usesa Hamming window such that x and y aredivided into eight segments with noverlap overlappingsamples.

For a list of available windows, see Windows.

Example: hann(N+1) and (1-cos(2*pi*(0:N)'/N))/2 bothspecify a Hann window of length N+1.

Data Types: single | double

noverlapNumber of overlapped samples
positive integer | []

Number of overlapped samples, specified as a positive integer.

  • If window is scalar, then noverlap mustbe smaller than window.

  • If window is a vector, then noverlap mustbe smaller than the length of window.

If you specify noverlap as empty,then mscohere uses a number that produces 50%overlap between segments. If the segment length is unspecified, thefunction sets noverlap to ⌊N/4.5⌋,where N is the length of the input and output signals.

Data Types: double | single

nfftNumber of DFT points
positive integer | []

Number of DFT points, specified as a positive integer. If youspecify nfft as empty, then mscohere setsthis argument to max(256,2p),where p=⌈log2N forinput signals of length N.

Data Types: single | double

freqrangeFrequency range for magnitude-squared coherence estimate
'onesided' | 'twosided' | 'centered'

Frequency range for the magnitude-squared coherence estimate,specified as 'onesided', 'twosided',or 'centered'. The default is 'onesided' forreal-valued signals and 'twosided' for complex-valuedsignals.

  • 'onesided' — Returns theone-sided estimate of the magnitude-squared coherence estimate betweentwo real-valued input signals, x and y.If nfft is even, cxy has nfft/2+1 rows and is computed over the interval [0,π] rad/sample.If nfft is odd, cxy has(nfft+1)/2rows and the interval is [0,π) rad/sample.If you specify fs, the corresponding intervalsare [0,fs/2] cycles/unit time for even nfft and[0,fs/2) cycles/unit time for odd nfft.

  • 'twosided' — Returns thetwo-sided estimate of the magnitude-squared coherence estimate betweentwo real-valued or complex-valued input signals, x and y.In this case, cxy has nfft rowsand is computed over the interval [0,2π) rad/sample.If you specify fs, the interval is [0,fs)cycles/unit time.

  • 'centered' — Returns thecentered two-sided estimate of the magnitude-squared coherence estimatebetween two real-valued or complex-valued input signals, x and y.In this case, cxy has nfft rowsand is computed over the interval (–π,π] rad/samplefor even nfft and (–π,π) rad/samplefor odd nfft. If you specify fs,the corresponding intervals are (–fs/2, fs/2]cycles/unit time for even nfft and (–fs/2, fs/2)cycles/unit time for odd nfft.

Output Arguments

collapse all

cxy — Magnitude-squared coherence estimate
vector | matrix | three-dimensional array

Magnitude-squared coherence estimate, returned as a vector,matrix, or three-dimensional array.

w — Normalized frequencies
vector

Normalized frequencies, returned as a real-valued column vector.

f — Frequencies
vector

Frequencies, returned as a real-valued column vector.

More About

collapse all

Magnitude-Squared Coherence

The magnitude-squared coherence estimate isa function of frequency with values between 0 and 1. These valuesindicate how well x corresponds to y ateach frequency. The magnitude-squared coherence is a function of thepower spectral densities, Pxx(f) and Pyy(f),and the cross power spectral density, Pxy(f),of x and y:

Cxy(f)=|Pxy(f)|2Pxx(f)Pyy(f).

For multi-input/multi-output systems, the multiple-coherencefunction becomes

CXyi(f)=PXyi(f)PXX1(f)PXyi(f)Pyiyi(f)=[Px1yi*(f)Pxmyi*(f)][Px1x1(f)Px1x2(f)Px1xm(f)Px2x1(f)Px2x2(f)Px2xm(f)Pxmx1(f)Pxmx2(f)Pxmxm(f)]1[Px1yi(f)Pxmyi(f)]1Pyiyi(f)

for the ithoutput signal, where:

  • X corresponds to the array of m inputs.

  • PXyi isthe m-dimensional vector of cross power spectraldensities between the inputs and yi.

  • PXX is the m-by-m matrixof power spectral densities and cross power spectral densities ofthe inputs.

  • Pyiyi isthe power spectral density of the output.

  • The dagger (†) stands for the complex conjugatetranspose.

Algorithms

mscohere estimates the magnitude-squaredcoherence function [2] using Welch’soverlapped averaged periodogram method [3], [5].

References

[1] Gómez González, A., J. Rodríguez, X. Sagartzazu,A. Schumacher, and I. Isasa. “Multiple Coherence Method inTime Domain for the Analysis of the Transmission Paths of Noise andVibrations with Non-Stationary Signals.” Proceedingsof the 2010 International Conference of Noise and Vibration Engineering,ISMA2010-USD2010. pp.3927–3941.

[2] Kay, Steven M. Modern SpectralEstimation. Englewood Cliffs, NJ: Prentice-Hall, 1988.

[3] Rabiner, Lawrence R., and Bernard Gold. Theoryand Application of Digital Signal Processing. EnglewoodCliffs, NJ: Prentice-Hall, 1975.

[4] Stoica, Petre, and Randolph Moses. SpectralAnalysis of Signals. Upper Saddle River, NJ: PrenticeHall, 2005.

[5] Welch, Peter D. “The Use of FastFourier Transform for the Estimation of Power Spectra: A Method Basedon Time Averaging Over Short, Modified Periodograms.” IEEE® Transactionson Audio and Electroacoustics. Vol. AU-15, 1967, pp. 70–73.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Version History

Introduced before R2006a

expand all

The mscohere function supports single-precision variable-size window inputs for code generation.

The mscohere function supports single-precision inputs.

See Also

cpsd | periodogram | pwelch | tfestimate

Topics

  • Cross Spectrum and Magnitude-Squared Coherence
  • Compare the Frequency Content of Two Signals

MATLAB Command

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.

Magnitude-squared coherence - MATLAB mscohere (14)

Select a Web Site

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:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

Contact your local office

Magnitude-squared coherence - MATLAB mscohere (2024)
Top Articles
Latest Posts
Article information

Author: Zonia Mosciski DO

Last Updated:

Views: 5807

Rating: 4 / 5 (51 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Zonia Mosciski DO

Birthday: 1996-05-16

Address: Suite 228 919 Deana Ford, Lake Meridithberg, NE 60017-4257

Phone: +2613987384138

Job: Chief Retail Officer

Hobby: Tai chi, Dowsing, Poi, Letterboxing, Watching movies, Video gaming, Singing

Introduction: My name is Zonia Mosciski DO, I am a enchanting, joyous, lovely, successful, hilarious, tender, outstanding person who loves writing and wants to share my knowledge and understanding with you.