MATLAB: Plotting the frequency spectrum

fftfrequencyplotspectrum

Hi,
I am having trouble plotting the frequency spectrum of a sine wave. For this code, i expect the main frequency component to be centered around 1/(2*pi), but they are not. Is there something I am missing in my code?
x = [0:0.1:2*pi];
y = sin(x);
z = fft(y);
z = fftshift(z);
N = length(y);
f = [-N/2:N/2-1]/N;
plot(f,abs(z))

Best Answer

Please try:
%%Time specifications:
Fs = 100; % samples per second
dt = 1/Fs; % seconds per sample
StopTime = 1; % seconds
t = (0:dt:StopTime-dt)';
N = size(t,1);
%%Sine wave:
Fc = 12; % hertz


x = cos(2*pi*Fc*t);
%%Fourier Transform:
X = fftshift(fft(x));
%%Frequency specifications:
dF = Fs/N; % hertz
f = -Fs/2:dF:Fs/2-dF; % hertz
%%Plot the spectrum:
figure;
plot(f,abs(X)/N);
xlabel('Frequency (in hertz)');
title('Magnitude Response');
HTH.
Rick
Related Question