MATLAB: About FFT of cosine function

dftfft

Hi, I have to calculate DFT of g(t)=cos(0.5*t). So I write the code below
>> N=128; %number of sampled time points
>> t=linspace(0,128,N); %time domain
>> Fs=1/(t(2)-t(1)); %sampling frequency
>> Fn=Fs/2; %Nyquist Frequency
>> g=cos(0.5*t); %input signal
>> G=fftshift(fft(g)/N); %Fourier transform of g
>> w=linspace(-Fn,Fn,N)*2*pi; %angular frequency domain
>> subplot(2,1,1)
>> plot(w,abs(G)); % to see amplitude
>> subplot(2,1,2)
>> plot(w,angle(G)); % to see phase
<The result of above code>
In this situation, my question is
1) In amplitude graph, I expected it has to have formation of two Dirac delta function Aδ(w-0.5)+Aδ(w+0.5), i.e., amplitude shoudn't have values at w=/0.5 and w=/-0.5. But it have values. How can I change the code to make this two delta functions?
2) In amplitude graph, I also expected the coordinates of peaks are (-0.5,0.5) and (0.5,0.5), but it is not. How can I change the code to make peaks at this coordinates??
Thank you..!!

Best Answer

Hi mk,
In order to get just the two sharp peaks you need to have exactly n oscillations in the time domain. Otherwise the wave is cut off partway through an oscillation and does not represent a continuous oscillatory wave.
The code below uses a total time of 4*pi so there are 8 oscillations in the time record. (Also, cos = 1 at t = 0, and exactly n oscillations means that there can't be a repeated point cos = 1 at the end of the time record).
w0 = .5;
T = 4*pi; % total time
N = 1000;
t = linspace(0,T,N+1); % N+1 points, N intervals
t(end) = []; % eliminate repeated point at the end
y = cos(w0*t);
z = fftshift(fft(y)/N);
% fft golden rule: delta_t*delta_w = 2*pi/N
% delta_w = 2*pi/(N*delta_t) = 2*pi/T
delw = 2*pi/T;
w = (-N/2:N/2-1)*delw;
r = [real(z);imag(z)];
stem(w,[real(z);imag(z)]')
xlim([-10 10])