Last active
October 28, 2024 15:25
-
-
Save doronbehar/01deb0041f9377fbe73266ad123c4ac4 to your computer and use it in GitHub Desktop.
What was fftshift created for?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import numpy as np | |
import matplotlib.pyplot as plt | |
N = 10_000 | |
t = np.linspace(-10, 10, N) | |
signal = np.exp(-t**2) | |
signal_f = np.abs(np.fft.fft(signal)) | |
fig, axs = plt.subplots(3,2) | |
axs[0,0].plot(signal_f) | |
axs[0,0].set_xlabel("index") | |
axs[0,0].set_title("No x given to plot") | |
dt = t[1]-t[0] | |
f = np.fft.fftfreq(N, dt) | |
axs[1,0].plot(f, signal_f) | |
axs[1,0].set_xlabel("f [Hz]") | |
axs[1,0].set_title("numpy's fftfreq (correct x axis array)") | |
f_shifted = np.fft.fftshift(f) | |
axs[0,1].plot(f_shifted, signal_f) | |
axs[0,1].set_title("The fftfreq array shifted with fftshift (wrong x axis array!)") | |
f_natural = np.linspace(-1/dt, 1/dt, N) | |
f_my = np.fft.fftshift(f_natural) | |
axs[1,1].plot(f_my, signal_f) | |
axs[1,1].set_title("fftshifting a manually created linspace (correct x axis array)") | |
signal_f_shifted = np.fft.fftshift(signal_f) | |
axs[2,1].plot(f_natural, signal_f_shifted) | |
axs[2,1].set_title("fftshifting the fft of the signal, with a linearly spaced frequencies as x axis array input (correct x axis array)") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TL;DR If you use Numpy and not Matlab, you should never need to use
fftshift
, asfftfreq
is much more declarative and understandable. If you use Matlab, the only way to get the correct frequency array, is to usefftshift
on thelinspace
created givendt
andN
- wheref_my
is created.