Alireza Hassani
Alireza Hassani

Reputation: 21

Converting Matlab code into Python - FFT

I need to convert a piece of MATLAB code to Python and I'm bad at both. The code in MATLAB uses fft and fftshift. I tried to use NumPy in Python. The code runs but when I compare the outcome they are not matching. I appreciate your help.

Here is the MATLAB code:

h(1,1:Modes_number) = -1i*S;
hfft = fft(h);
hft0 = fftshift(hfft);

and here is the Python code which I wrote:

h = np.zeros((1,self.cfg.Modes_number+1),dtype=complex) 
for i in range(0, self.cfg.Modes_number+1):
   h[0,i] = -1j*S;

hfft = np.fft.fft(h)
hft0 = np.fft.fftshift(hfft)

Here is the values for S and Modes_number:

S = 12.5022214424;
Modes_number = 200;

Here is also an example of the results I get in MATLAB and Python:

MATLAB:
hfft(1,1)
ans =
   1.1857e-13 - 2.5129e+03i

Python:
hfft[0]
0. -2.52544873e+03j

Cheers.

Upvotes: 0

Views: 1194

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60554

The error in your Python code is that you define h to be of size Modes_number+1, which is one more than the size in the MATLAB code. The first value in hfft is the sum of all input values. In MATLAB this is -1j*S*200 = -2500.4j, and in your Python code this is -1j*S*201 = -2512.9j. These are the values that you are seeing.

This bit of Python code produces the same as your bit of MATLAB code, up to numerical precision (I see some values like -1.68388521e-15 +6.55829989e-15j in Python, which are forced to 0 by MATLAB's algorithms). I am creating h as a one-dimensional vector, rather than a 2D array with one dimension of size 1.

import numpy as np

S = 12.5022214424
Modes_number = 200
h = np.zeros(Modes_number,dtype=complex)
for i in range(0,Modes_number):
   h[i] = -1j*S;
hfft = np.fft.fft(h)
hft0 = np.fft.fftshift(hfft)

Python:

>>> hfft[0]
-2500.4442884800001j

MATLAB:

>> hfft(1)
ans = 
   0.000000000000000e+00 - 2.500444288480000e+03i`

Upvotes: 1

Related Questions