FFT results Matlab VS Numpy (Python): not the same results… here is a solution to the problem.
FFT results Matlab VS Numpy (Python): not the same results
I have a Matlab script to calculate the DFT of the signal and plot it :
(Data can be seenhere).
clc; clear; close all;
fid = fopen('s.txt');
txt = textscan(fid,'%f');
s = cell2mat(txt);
nFFT = 100;
fs = 24000;
deltaF = fs/nFFT;
FFFT = [0:nFFT/2-1]*deltaF;
win = hann(length(s));
sw = s.*win;
FFT = fft(sw, nFFT)/length(s);
FFT = [FFT(1); 2*FFT(2:nFFT/2)];
absFFT = 20*log10(abs(FFT));
plot(FFFT, absFFT)
grid on
I’m trying to translate it into Python but can’t get the same result.
import numpy as np
from matplotlib import pyplot as plt
x = np.genfromtxt("s.txt", delimiter=' ')
nfft = 100
fs = 24000
deltaF = fs/nfft;
ffft = [n * deltaF for n in range(nfft/2-1)]
ffft = np.array(ffft)
window = np.hanning(len(x))
xw = np.multiply(x, window)
fft = np.fft.fft(xw, nfft)/len(x)
fft = fft[0]+ [2*fft[1:nfft/2]]
fftabs = 20*np.log10(np.absolute(fft))
plt.figure()
plt.plot(ffft, np.transpose(fftabs))
plt.grid()
I get the diagram (Matlab on the left, Python on the right):
What am I doing wrong?
Solution
In one case of connecting two lists, the two codes are different
FFT = [FFT(1); 2*FFT(2:nFFT/2)];
In MATLAB code
In the other, the first value of fft is added to the rest of the vector
fft = fft[0]+ [2*fft[1:nfft/2]]
‘+’ Don’t concatenate here because you have numpy arrays
In Python, it should be:
fft = fft[0:nfft/2]
fft[1:nfft/2] = 2*fft[1:nfft/2]