I'm working on a project where I calculate the phase angle between two signals. But to keep the math/code simple I'm using simple sine/cosine function to generate the signal.
My method is as follows -
Generate Sine/Cosine signals
Select a sample size of the signal (to specify specific 'snap-shots' of the signal to be analysed)
Apply Hanning Window (since signal is non-periodic in my application)
Buffer the signal with 10 sample overlap (to do rolling FFT)
Take FFT of both buffered signals
Take the average of the FFT
Now extract the phase of the harmonic with the largest amplitude
Take the difference between the two phases.
Now, In my case since I have sine and cosine, shouldn't I get 90°
as my phase difference?
I instead get either 0
,-180
,180
for each sample.
Thanks for your help!!
Here's my Code -
Fs=100;
x=0:0.1:32;
ISin=sin(x);
ICos=cos(x);
s = length(ISin);
samplesize=16;
Displacement=zeros(samplesize,1);
Input=zeros(samplesize,1);
n=1;
p=1;
j=1;
for i=1:s
Displacement(j,1)=ICos(i);
Input(j,1)=ISin(i);
if n==samplesize
NFFT = 2^nextpow2(samplesize); % Next power of 2
%% Create Hanning Window and Buffer the Data
window=hann(NFFT);
Displacement_Buffered=buffer(Displacement,NFFT,10);
Input_Buffered=buffer(Input,NFFT,10);
Displacement_Buffered=Displacement_Buffered'*diag(window);
Input_Buffered=Input_Buffered'*diag(window);
%% Calculate the FFT of the Signals now
Displacement_FFT=fft(Displacement_Buffered,NFFT)/samplesize;
Input_FFT=fft(Input_Buffered,NFFT)/samplesize;
%Calculate the length of the frequency axis to be displayed
f = Fs/2*linspace(0,1,NFFT/2+1);
%Take the average
Displacement_FFT=mean(Displacement_FFT);
Input_FFT=mean(Input_FFT);
%Calculate the phase angles
Displacement_Phase=(angle(Displacement_FFT));
Input_Phase=(angle(Input_FFT));
%Identify the largest component
[Displacement_Max_Value Displacement_Max_Index]=max(abs(Displacement_FFT));
[Input_Max_Value Input_Max_Index]=max(abs(Input_FFT));
%Get the Phase angles that correspond to the largest harmonic
Z_Displacement=Displacement_Phase(Displacement_Max_Index);
Z_Input=Input_Phase(Input_Max_Index);
%Calculate the Phase angle differences
Z_Displacement_Input=Z_Displacement-Z_Input;
%Consolidate them in a matrix
DispvsInput(p,1)=Z_Displacement_Input*180/pi;
p=p+1;
j=1;
n=1;
end
%Counter
n=n+1;
j=j+1;
end
plot(DispvsInput)
xlabel('Sample Number')
ylabel('Phase Difference(deg)')
title('Phase Difference between Sine and Cosine')
The term 'DispvsInput' gives the phase difference between the two signals for each sample size.