MATLAB Answers

aaa

plotting the frequency spectrum

Asked by aaa
on 24 Apr 2012
Latest activity Answered by phanindra reddy on 21 May 2015 at 5:27

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

  0 Comments

Products

No products are associated with this question.

3 Answers

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

  0 Comments


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

  1 Comment

Elige Grant
on 24 Apr 2012

Forgot the "== 0" in the if statement... whoops!


Answer by phanindra reddy on 21 May 2015 at 5:27

Hi every one

could you please plot spectrum for the variables that are in EXCEL file which is attached.?

thanks.

Please provide me code also.

Phanindra

  0 Comments


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply today