MATLAB Answers

0

How to execute fft and ifft

Asked by Maxilyn Tan on 11 Aug 2015
Latest activity Commented on by Venkat Ta on 31 Oct 2017
I tried to execute this code but for some reason the graph of the ifft is not a perfect sine wave. Can someone please instruct me as to what I did wrong? I got the fft code from the internet and I want to get the ifft
Main Code
fo = 4; %frequency of the sinewave
Fs = 100; %sampling rate
Ts = 1/Fs; %sampling time interval
t = 0:Ts:1-Ts;
n = length(t); %number of samples
y = sin(2*pi*fo*t);
figure(1)
plot(t,y)
grid on
[YfreqD,freqRng] = positiveFFT(y,Fs);
figure(2)
stem(freqRng,abs(YfreqD));
B = ifft(YfreqD)*length(y);
t1 = (0:(1-Ts)/(length(B)-1):1-Ts);
figure(3)
plot(t1,B)
grid on
Positive fft code
function[X,freq] = positiveFFT(x,Fs)
N = length(x);
k = 0:N-1;
T = N/Fs;
freq = k/T; %create the frequency range
X = fft(x)/N; %normalize the data
cutOff = ceil(N/2);
X = X(1:cutOff);
freq = freq(1:cutOff);

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by David Sanchez
on 11 Aug 2015
 Accepted Answer

Hi thereb, the sine wave is right there, but the problem is that after FFTing the your y data, YfreqD contains half the samples than the original. When calculating the iFFT, that length is kept and plot(t1,B) plots half the original data.
You can try plot like this to see the points you are plotting in each case:
figure(1)
plot(t,y,t,y,'r*')
figure(3)
plot(t1,B,t1,B,'r*')
You can add a higher sampling rate at the beginning of your code and your figure(3) will appear like a less "straight" sine wave.
fo = 4; %frequency of the sinewave
Fs = 200; %sampling rate
Ts = 1/Fs; %sampling time interval
t = 0:Ts:1-Ts;
n = length(t); %number of samples
y = sin(2*pi*fo*t);
figure(1)
plot(t,y,t,y,'r*')
grid on
[YfreqD,freqRng] = positiveFFT(y,Fs);
figure(2)
stem(freqRng,abs(YfreqD));
B = ifft(YfreqD)*length(y);
t1 = (0:(1-Ts)/(length(B)-1):1-Ts);
figure(3)
plot(t1,B,t1,B,'r*')
grid on

  1 Comment

I see what you mean, thank you very much!

Sign in to comment.


Answer by Shaohui Yong on 24 Jul 2017

This is really helpful, thanks!

  1 Comment

Thanks. The code is fine, is there any possible chance to get no complex values of B sine wave same like as input y ?
suppose if I plot like as plot(t,y,'b',t1,real(B),'r--') with Fs=200; there is so much differences between input Y and ifft B.
Is it good choice to take real(B)?

Sign in to comment.