MATLAB: How to extract the correct phase of a sine wave from data

digital signal processingffthelpMATLABsignalsignal processingSignal Processing Toolbox

Hi everyone
I'm trying to write a code which allows me to determine the phase of a sine wave from its vector.
given: the sinusoidal signal vector, its frequency
unknown: its phase
I have tried with this code but i don't understand why do i end up getting wrong/ unprecise results
a=0; b=800; %time intervalls
N=20000; %N number of samples
t=linspace(a,b,N); %time vector
ts=(b-a)/N; %sampling time
fs=1/ts; %sampling frequency
fn=fs/2; %Nyquist frequency
fx=1; phix= 180; %Frequency and phase of x(t)
x=sin(2*pi*fx.*t+phix* (pi/180)); %Original signal
binwidth = 1 / (b-a); % frequency binwidth in Hz
f_index = fx / binwidth +1; % frequency index
y = abs(fft(x)) / (N/2);
phase = angle(fft(x))* 180/pi+90;
disp(phase(f_index));
for example here i get 187.2000 instead of 180
I'd be very grateful for your help and clarifications!

Best Answer

The reason you get imprecise results is because you are using discrete fourier transform. When you get the phase of the frequency bin from fft, you get, roughly speaking, the phase of a frequency bin, but not the phase of a single frequency. You can get much better estimation if you analyse a few neighboring bins, but that’s a complex process.
If you’d like to compute exact phase and you know the signal is exactly sinusoidal, you’d better just use asin(x(1)).