Manual DFT and IDFT Implementation in MATLAB/Octave
Implementing DFT and IDFT Manually in MATLAB/Octave
This document provides the complete MATLAB/Octave code for generating a sinusoidal signal, calculating its Discrete Fourier Transform (DFT) manually, and then reconstructing the original signal using the Inverse Discrete Fourier Transform (IDFT).
1. Signal Setup and Initialization
We begin by clearing the workspace and defining the time vector and the sinusoidal signal. The code uses 1-based indexing typical of MATLAB/Octave.
clear all; clc; close all; n = 1:100; % Time definition (100 samples) x = cos(2*pi*0.1*n); % Generate sinusoid signal in time domain N = length(x); % Sequence length for N-point FFT/DFT
2. Manual Discrete Fourier Transform (DFT) Calculation
The DFT is calculated using nested loops based on the fundamental formula: $X(k) = \sum_{n=0}^{N-1} x(n) e^{-i 2 \pi k n / N}$.
for k = 1:N % For every frequency index k
y(k) = 0;
for n = 1:N % For every time index n
% Calculate DFT component y(k)
y(k) = y(k) + x(n) * exp(-i*2*pi*(k-1)*(n-1)/N);
end
end
% y now contains the frequency domain representation
3. Plotting Time and Frequency Domains
We visualize the original signal and the magnitude spectrum of the calculated DFT.
Time Domain Visualization
t = 0:N-1;
subplot(3,1,1);
stem(t,x); % Plotting discrete signal
title('Sinusoidal Waveform in the Time Domain');
Frequency Domain Visualization
magnitude = abs(y); % Absolute values of individual FFT complex components
w = 0:N-1;
subplot(3,1,2);
stem(w,magnitude);
title('Sinusoid Waveform in Frequency Domain using DFT');
4. Manual Inverse Discrete Fourier Transform (IDFT)
The IDFT reconstructs the original signal $x$ from the frequency components $y$. The IDFT formula requires a positive exponential sign and the scaling factor $1/N$. $R$ is used here for clarity, where $R=N$.
R = length(y); % Length of the DFT array
for n = 1:R
x1(n) = 0;
for k = 1:R % Loop as per the IDFT formula
% IDFT Formula: x(n) = (1/R) * sum(X(k) * exp(i*2*pi*(k-1)*(n-1)/R))
x1(n) = x1(n) + y(k) * exp(i*2*pi*(k-1)*(n-1)/R);
end
x1(n) = x1(n) / R; % Apply the scaling factor 1/R
end
5. Plotting the Reconstructed Signal
The final subplot displays the reconstructed signal x1, verifying the accuracy of the manual IDFT implementation.
subplot(3,1,3);
stem(t, real(x1)); % Plotting the real part of the reconstructed signal
title('Reconstructed Signal using IDFT');
xlabel('Sample Index (n)');
ylabel('Amplitude');
