Stefano Fedele - 2 months ago 17

Python Question

The aim of this post is to properly understand Numerical Fourier Transform on Python or Matlab with an example in which the Analytical Fourier Transform is well known. For this purpose I choose the rectangular function, the analytical expression of it and its Fourier Transform are reported here

https://en.wikipedia.org/wiki/Rectangular_function

Here the code in Matlab

`x = -3 : 0.01 : 3;`

y = zeros(length(x));

y(200:400) = 1;

ffty = fft(y);

ffty = fftshift(ffty);

plot(real(ffty))

And here the code in Python

`import numpy as np`

import matplotlib.pyplot as plt

x = np.arange(-3, 3, 0.01)

y = np.zeros(len(x))

y[200:400] = 1

ffty = np.fft.fft(y)

ffty = np.fft.fftshift(ffty)

plt.plot(np.real(ffty))

In both the two programming langueages I have the some result with the some problems:

First of all the fourier transfrom is not real as expected, moreover even choosing the real part, the solution does not looks like the analytical solution: in fact the first plot reported here is as it should be at least in shape and the second plot is what I get from my calculations.

Is there anyone who could suggest me how to analytically calculate the fourier transform of the rectangular function?

Answer

There are two problems in your Matlab code:

First, `y = zeros(length(x));`

should be `y = zeros(1,length(x));`

. Currently you create a square matrix, not a vector.

Second, the DFT (or FFT) will be real and symmetric if `y`

is. Your `y`

should be symmetric, and that means with respect to `0`

. So, instead of `y(200:400) = 1;`

use `y(1:100) = 1; y(end-98:end) = 1;`

. Recall that the DFT is like the Fourier series of a signal from which your input is just one period, and the first sample corresponds to time instant 0.

So:

```
x = -3 : 0.01 : 3;
y = zeros(1,length(x));
y(1:100) = 1; y(end-98:end) = 1;
ffty = fft(y);
ffty = fftshift(ffty);
plot(ffty)
```

gives

```
>> isreal(ffty)
ans =
1
```