MATLAB: How to apply Inverse FFT after filtering to get the original signal back

fftifft

I have applied FFT on a mixed signal to find its component. Then I used low pass filtering to separate specifc signal component. However, when I applied inverse IFFT, I did not get the original signal back (the signal before the FFT). I think I made a mistake while applying inverse FFT. Could you please help me with that?
Here is the code I used:
clc
clear all;
close all;
format long
m=1000; I1=0.5; I2=0.3; I3=0.2; L1=100*m; L2=1000*m; n1=1; n2=1.446;
lam1=1520; lam2=1580;
inc=(lam2-lam1)/(2^12-1);
lam=lam1:inc:lam2;
Q12=(4*pi*n1*L1)./lam;
Q23=(4*pi*n2*L2)./lam;
Q13=Q12+Q23;
I_first=I1+I2+2*sqrt(I1*I2).*cos(Q12); % first signal
I_second=I2+I3+2*sqrt(I2*I3).*cos(Q23); % second signal
I_third=I1+I3+2*sqrt(I1*I3).*cos(Q13); % third signal
I=I1+I2+I3+2*sqrt(I1*I2).*cos(Q12)+2*sqrt(I2*I3).*cos(Q23)+2*sqrt(I1*I3).*cos(Q13); % Mixed signal
figure(1)
subplot(4,1,1);plot(lam,I_first); subplot(4,1,2);plot(lam,I_second);subplot(4,1,3);plot(lam,I_third);subplot(4,1,4);plot(lam,I);
%FFT
fs=500;fn=fs/2;N=length(I);nfft=N;
FT=fft(I);
f=fs*(0:nfft-1)/nfft;
ff=fs*(0:nfft/2-1)/nfft;
FT2=FT(1:nfft/2); % positive half
[p,l]=findpeaks(abs(FT2),ff);
figure(2)
subplot(2,1,1);plot(f,abs(FT)); subplot(2,1,2);plot(ff,abs(FT2));
%Hamming window
figure(3)
f1=l(1); f2=l(2); f3=l(3); freq=[f1 f2 f3];
mm=(0.1*f1)/(fs/2);%define tansition bandwidth
M=round(8/mm);%define the window length
NN=M-1;%define the order of filter
b=fir1(NN,1*f1/(fs/2));%use the firl function to design a filter
[h,f]=freqz(b,1,512);%amplitude-frequency characteristic graph
plot(f*fs/(2*pi),20*log10(abs(h)))
xlim([0 10]);
%wavelength domain
figure(4)
sf=filter(b,1,I);
subplot(3,1,1)
plot(lam,sf) % plot wavelength domain signal after filtering
Fsf=fft(sf,512);%frequency-domain diagram after filtering
AFsf=abs(Fsf);%the amplitude
f=(0:255)*fs/512;%frequency sampling
subplot(3,1,2)
plot(f,AFsf(1:256))%plot the frequency domain diagram after filtering
y=ifft(Fsf); % IFFT
subplot(3,1,3)
plot(y)

Best Answer

You would have to use fftshift and then apply the results of freqz symmetrically to each half of the complex fft result, so using it on the right half and flipping it for the left half, then doing element-wise multiplication, then using ifftshift to reverse it, and then doing the inverse fft. (I have done that in another Answer that I cannot now locate, and it is more trouble than it is worth.)
A much easier way to do what you want (with all the complicated bits already solved) is to use the fftfilt function. It will use your ‘b’ vector from the FIR filter you already designed. I strongly recommend that approach!