I am trying to write my own inverse DFT function in MATLAB as I need a subset of these Fourier mode basis in real space for an application. However, when I check my inverse DFT routine after extracting the Fourier coefficients against Matlab’s ifft function and the original waveform there seems to be a slight error. The code is seen from below.
% 1D fft and inverse fft
clear; clc; close all;
L=1; % total domain size
n=100;
x=linspace(0,L,n); %define x values
dx=x(1)-x(2);
F=1*cos(2*pi*5*x); %declare the function
figure(1)
plot(x,F,'linewidth',2,'Displayname','Original');
Fhat=fftshift(fft(F));%compute fft and shift to center
if(mod(n,2)==0) % even split
dk=2*pi/L.*[-n/2:1:1:n/2-1];
else %odd split
dk=2*pi/L*[-(n-1)/2:1:(n-1)/2];
end
figure % plot FFt results
plot(dk/(2*pi),abs(Fhat),'displayname','Frequency')
% Now here is my inverse fft
f=zeros(1,n);
for i=1:n
f=f+Fhat(i).*exp(1j*dk(i).*x)
end
f=f*1/n;
figure(1); hold on;
plot(x,real(f),'b-.','linewidth',2,'displayname','From my own invDFT')
plot(x,ifft(ifftshift(Fhat)),'M--','linewidth',2,'displayname','From matlab ifft')
xlabel('x','fontsize',16)
ylabel('y','fontsize',16)
legend()
Below is an image showing the discrepancy between the waveforms.
Comparison of methods
I’m not sure if this issue is a floating point problem or if my frequency bins are incorrect. This is my first time using fft. Any insight is greatly appreciated.
Mart is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.