0

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.

3
  • I'm not good at Python either, but I would keep that purely 1D, rather than 2D with a singleton dimension as is standard in MATLAB: h=np.zeros(self.cfg.Modes_number,dtype=complex) Commented May 8, 2018 at 22:54
  • Did the above comment help? If not, please let us know the value of Modes_number and S, without those we cannot reproduce what you see. Commented May 14, 2018 at 6:31
  • Hi Cris, Thanks for you reply and follow up. Unfortunately, I couldn't fix it using your hint. Here is the values for S and Modes_number: code S=12.5022214424 code 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 Commented May 15, 2018 at 2:33

1 Answer 1

1

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`
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.