Amrmsmb
Amrmsmb

Reputation: 11416

how to get fourier transform of a signal

In the below code I am trying to get the fourier transform of a stationary signal (x3). But at run time the plot i get is absolutely something wrong and does not show any frequencies of the signals x3.

kindly please guide me and help me to get the fourier transform correctly.

Code:

 %% Time specifications:
  Fs = 8000;                       % samples per second
  dt = 1/Fs;                       % seconds per sample
 StopTime = 1;                    % seconds
 t = (0:dt:StopTime-dt);         % seconds

 x1 = (10)*cos(2*pi*3*(t));
 x2 = x1 + (10)*cos(2*pi*5*(t));
 x3 = x2 + (10)*cos(2*pi*10*(t));


 %% here i try to Plot fourier transform of the signal x3:
 NFFT = 2^nextpow2(StopTime); % Next power of 2 from length of y
 Y = fft(y,NFFT)/StopTime;
 f = Fs/2*linspace(0,1,NFFT/2+1);
 figure;
 plot(f,2*abs(Y(1:NFFT/2+1)));

 %% Plot the signal versus time:
 figure;
 hold on;
 plot(t,x1,'r');
 plot(t,x2,'g');
 plot(t,x3,'b');

Update_1 enter image description here

enter image description here

Upvotes: 0

Views: 558

Answers (1)

mehmet
mehmet

Reputation: 1631

You can not see what you expected because the value of NFFT is 1 means when you write NFFT/2+1 as an index of Y it will not be an integer value so MATLAB warns you. You can calculate NFFT like this:

NFFT = 2^nextpow2(length(t))

instead of writing

NFFT = 2^nextpow2(StopTime)

Well, try this:

Fs       = 8000;                 % samples per second
dt       = 1/Fs;                 % seconds per sample
StopTime = 1;                    % seconds
t        = (0 : dt : StopTime-dt);   % seconds

x1 = 10 * cos(2*pi*3*t);
x2 = x1 + 10 * cos(2*pi*5*t);
x3 = x2 + 10 * cos(2*pi*10*t);


%% here i try to Plot fourier transform of the signal x3:
NFFT = 2 ^ nextpow2(length(t));     % Next power of 2 from length of y
Y    = fft(x3, NFFT) / StopTime;
f    = Fs / 2 * linspace(0, 1, NFFT/2 + 1);
figure;
plot(f, 2 * abs( Y( 1:length(f) ) ) ); % // Also try this: plot(f(f <= 200), 2 * abs( Y( 1:length(f(f <= 200)) ) ) )

%% Plot the signal versus time:
figure;
hold on;
plot(t, x1, 'r');
plot(t, x2, 'g');
plot(t, x3, 'b');

Plots:

enter image description here enter image description here

EDIT:

1- Actually you don' t have to use nextpow() function. If you use it, fft() function works faster. Because, due to time efficiency, fft() works like that recursively divide the signal by 2 for each time. Then calculates discrete fourier transform for each part and gather them. This means that the FFT is most efficient when the signal vector length is a power of 2.

2- Dividing fft result by StopTime part doesn' t make any sense to me either. Dividing fft result by NFFT may be more convenient theoretically.

Upvotes: 1

Related Questions