Explore DFT frequency accuracy, got stuck
Show older comments
I'm trying to analyze the frequency accuracy of the DFT as a function of DFT size assuming a rectangular
window. Using single sinusoidal waveform sampled at 5 kHz vary its frequency in small
increments to show the how the frequency accuracy changes for at least 4 different DFT length,
256, 512, 1024, and 4096.
Here is my code:
%Part 1
% MATLAB code to analyze the frequency accuracy of the DFT manually
fs = 5000; % Sampling frequency 5 kHz
f_start = 1000; % Start frequency of sinusoid (1 kHz)
f_end = 1050; % End frequency of sinusoid (1.05 kHz)
f_step = 1; % Frequency step size (small increments)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% DFT sizes to analyze
N_dft = [256, 512, 1024, 4096];
% Prepare figure
figure;
hold on;
for N = N_dft
freq_accuracy = []; % Store accuracy results for each DFT size
for f = f_start:f_step:f_end
% Generate sinusoidal waveform
x = sin(2*pi*f*t);
rectangular_window = rectwin(N)';
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
% Manually compute the DFT
X = x_windowed*dftmtx(N);
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Find the index of the peak in the magnitude of the DFT
[~, peak_idx] = max(abs(X));
% Estimated frequency from the DFT
f_estimated = freq_axis(peak_idx);
% Store the frequency error (absolute difference between true and estimated frequency)
freq_error = abs(f_estimated - f);
freq_accuracy = [freq_accuracy, freq_error];
end
% Plot the frequency accuracy for the current DFT size
plot(f_start:f_step:f_end, freq_accuracy, 'DisplayName', ['N = ', num2str(N)]);
end
% Add labels and legend
xlabel('True Frequency (Hz)');
ylabel('Frequency Error (Hz)');
title('Frequency Accuracy of the DFT for Different DFT Sizes (Manual DFT)');
legend('show');
grid on;
hold off;
However, the result I got is really weird. 

At some frequency the estimate error between true frequency can be 3000, while most of the time it's under 1.
However, it I substitue this line: X = x_windowed*dftmtx(N);
with this line: X = fft(x_windowed, N);
Then I got this image

It seems that this is the correct figure.
I read from this website that fft and dftmtx function can be interchangeble
But my results doesn't approve it. I want to know why.
Besides, am I applying windowing function in a correct way?
The code is as following:
rectangular_window = rectwin(N)';
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
Accepted Answer
More Answers (0)
Categories
Find more on Modulation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!