MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by aaa on 24 Apr 2012

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))

*No products are associated with this question.*

Answer by Rick Rosson on 24 Apr 2012

Accepted 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

Answer by Elige Grant on 24 Apr 2012

Your "f" looks off. For your configuration (which uses fftshift):

N = length(y); dt = x(2)-x(1); % Time increment Nyq = 1/(2*dt); % Nyquist frequency df = 1/(N*dt); % Frequency increment if mod(N,2) == 0 % N is even f = -Nyq : df : Nyq-df; else % N is odd f = [sort(-1*(df:df:Nyq)) (0:df:Nyq)]; end

## 0 Comments