In this article, we imposed Matlab fft on a periodic function and to get its amplitude and phase
code
sampleFreq=100;
x=[-100:1/sampleFreq:100-1/sampleFreq];
nLength=length(x);%20000
fftLength=floor(nLength/2);
frequencyVector=(0:1/nLength*sampleFreq:(nLength-1)/nLength*sampleFreq);
y1=1.7*cos(10*2*pi*x+pi/4);
result=fft(y1,nLength);
result1=result(1:fftLength);
phase=atan2(imag(result1),real(result1));
result=2*abs(result)/nLength;
%plot(y1);
figure;
plot(frequencyVector(1:fftLength),result(1:fftLength));
xlabel("frequency")
ylabel("amplitude")
grid on;
%hold on;
%plot(frequencyVector(1:fftLength),phase(1:fftLength));
maxAmpli=max(result)
index=find(result==maxAptil)
thisPhase=phase(index(1))
freq=frequencyVector(index(1))
result
result 1:
result 2:
maxAmpli =
1.7000
index =
2001 18001
thisPhase =
0.7854
freq =
10
Note:
- If the function is relating to sin(), the correct phase should plus pi/2 due to the fft function is powered by cos() in matlab.
- To get right phase, the number of sample points should be even due to unknown error.