%% Coherence Function
% The magnitude-squared coherence between two signals x(n) and y(n) is
% C_{xy}(\omega)={{\left|P_{xy}(\omega)\right|^2}
% \over{P_{xx}(\omega)P_{yy}(\omega)}}.
% This quotient is a real number between 0 and 1 that measures the correlation between x(n) and y(n) at the frequency \omega.
% The mscohere function takes sequences xn and yn, computes their power spectra and CPSD, and returns the quotient of the magnitude squared of the CPSD and the product of the power spectra. Its options and operation are similar to the cpsd and tfestimate functions.
% Generate a signal consisting of two sinusoids embedded in white Gaussian noise. The signal is sampled at 1 kHz for 1 second.

rng('default')

fs = 1000;
t = (0:fs)/fs;
A = [1 2];                % Sinusoid amplitudes
f = [150;140];            % Sinusoid frequencies

xn = A*sin(2*pi*f*t) + 0.1*randn(size(t));

%
% Filter the signal xn with an FIR moving-average filter. Compute and plot the coherence function of xn and the filter output yn as a function of frequency.

h = ones(1,10)/10;
yn = filter(h,1,xn);

mscohere(xn,yn,256,128,256,fs)

% If the input sequence length, window length, and number of overlapping data points in a window are such that mscohere operates on only a single record, the function returns all ones. This is because the coherence function for linearly dependent data is one.
% Copyright 2015 The MathWorks, Inc.