DFT Software Implementation
The following functions perform real DFT computation.
MATLAB#
function [a, b] = dft(x)
% Compute the DFT of a real input signal
N = length(x); % Number of samples
n = 0 : N-1; % Sample indices
phi = 2 * pi * (n' * n) / N; % Compute angles for DFT matrix
% Compute cosine and sine frequency components
a = (2 / N) * cos(phi) * x;
b = (2 / N) * sin(phi) * x;
end
Python#
def dft(x):
""" Compute DFT of a real input signal """
N = len(x)
n = np.arange(N).reshape(1, N) # Create row vector
phi = 2 * np.pi * n.T * n / N # Compute angles for DFT matrix
# Compute cosine and sine frequency components
a = (2 / N) * np.dot(np.cos(phi), x)
b = (2 / N) * np.dot(np.sin(phi), x)
return a, b
C#
void dft(double x[], double a[], double b[], int N) {
// Compute DFT of a real input signal
for (int k = 0; k < N; k++) {
a[k] = 0.0;
b[k] = 0.0;
for (int n = 0; n < N; n++) {
double phi = 2 * PI * k * n / N;
a[k] += (2.0 / N) * x[n] * cos(phi);
b[k] += (2.0 / N) * x[n] * sin(phi);
}
}
}