Skip to content

Instantly share code, notes, and snippets.

@gorbatschow
Created December 2, 2021 22:33
Show Gist options
  • Save gorbatschow/90a664fe62791c9733e4febf6a021641 to your computer and use it in GitHub Desktop.
Save gorbatschow/90a664fe62791c9733e4febf6a021641 to your computer and use it in GitHub Desktop.
Matlab etude demonstrates window function effect on single-tone signal
% Spectral analysis etudes
% This etude demonstrates window function effect on single-tone signal
% code by [email protected]
clear
% PARAMETERS
% -------------------------------------------------------------------------
% Sample rate (Hz)
Fs = 48e3;
% Time resolution (secs)
dt = 1/Fs;
% Number of signal samples
NSIG = 2^10;
% Number of FFT input samples (zero padded signal samples)
NFFT = 2^14;
% Actual frequency resolution (Hz)
df = Fs/NSIG;
% Interpolated frequency resolution (Hz)
dfi = Fs/NFFT;
% Window functions
w_list = {'rectwin' 'hamming' 'hann' 'flattopwin' 'blackmanharris'};
nw = numel(w_list);
% Signal frequency (Hz)
fsig = df*100;
% Signal amplitude 0-pk (Volts)
asig = 1.0;
% GENERATOR
% -------------------------------------------------------------------------
% Generate tone signal
t = (0:NSIG-1)*dt;
s = asig*sin(2*pi*fsig*t);
% PROCESSOR
% -------------------------------------------------------------------------
S = zeros(nw, NFFT/2-1);
for i = 1:nw
% Calculate win. coef.
w = window(w_list{i}, NSIG)';
w = w/mean(w);
x = [s.*w zeros(1,NFFT-NSIG)];
X = fft(x, NFFT);
X = X(2:NFFT/2); % X(1) is DC
X = abs(X);
% Multiply by 2 for 0-Pk amplitude
X = X/NSIG*2;
% Store
S(i,:) = X;
end
% RESULTS
% -------------------------------------------------------------------------
% Interpolated spectrum frequnecies (Hz)
f = (1:NFFT/2-1)*dfi;
f_khz = f*1e-3;
fsig_khz = fsig*1e-3;
figure;
plot(f_khz, S');
grid on; grid minor;
xlim([fsig_khz-1 fsig_khz+1]);
ylim([0 1.1*max(asig)]);
xlabel('кГц'); ylabel('Pk-Pk');
legend(w_list);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment