# Coherence

$$\ For \ coherence, {F_s \over N} = {F_i\over M}$$ \ \begin{align} F_s = sampling \ rate \\ N = number \ of \ samples \\ F_i = signal \ frequency \ or \ frequency \ of \ interest \\ M = no. \ of \ cycles \ or \ bins \\ \end{align}

			
%  coherence and energy spreading in FFT
clc; clear;

fi = 15e3;
N = 1024; % samples
M = 17; % no. of cycles/bin
fs = fi/M*N; % sample rate for coherency

t = (0:N-1)/fs; % time vector
x = sin(2*pi*fi*t); % signal

subplot(3,1,1);
plot(t,x); % time domain signal
xlabel('time');
ylabel('amplitude');
title('signal');

% coherent sampling
y = fft(x,N); % fft
Y = abs(y(1:N/2+1)); % single-sided
Ydb = mag2db(Y); % convert to db
Ydb = Ydb - max(Ydb);
f = fs/2*linspace(0,1,N/2+1); % freq vector

subplot(3,1,2);
plot(f,Ydb); % coherent FFT
xlabel('freq');
ylabel('magnitude');
grid on;
title('FFT');

N = 1020; % leave the last 4 samples to make it non-coherent
y = fft(x,N); % fft
Y = abs(y(1:N/2+1)); % single-sided
Ydb = mag2db(Y); % convert to db
Ydb = Ydb - max(Ydb);
f = fs/2*linspace(0,1,N/2+1); % freq vector

subplot(3,1,3); 