w3resource

Perform 2D discrete Fourier Transform using SciPy's fftpack

NumPy: Integration with SciPy Exercise-2 with Solution

Write a NumPy program to generate a 2D array and performs a discrete Fourier transform using SciPy's fftpack module

Sample Solution:

Python Code:

# Import necessary libraries
import numpy as np
from scipy.fftpack import fft2

# Generate a 2D NumPy array of random numbers
data = np.random.rand(4, 4)

# Perform a 2D discrete Fourier transform using SciPy's fft2 function
dft_result = fft2(data)

# Print the original array
print("Original 2D array:")
print(data)

# Print the DFT result
print("\nDFT of the 2D array:")
print(dft_result)

Output:

Original 2D array:
[[0.16204087 0.71466796 0.27190299 0.16085316]
 [0.94790095 0.40448638 0.64383355 0.36492436]
 [0.2436009  0.74392168 0.39621449 0.48598625]
 [0.59709283 0.43888981 0.40708137 0.63237158]]

DFT of the 2D array:
[[ 7.61576914-0.j          0.23160316-0.65783047j -0.27643324-0.j
   0.23160316+0.65783047j]
 [-0.56025834-0.28570964j -0.19029233-0.40993533j  0.14851528-0.88941094j
   0.27579526+0.18182345j]
 [-1.25739254-0.j         -0.75655458-0.96566998j -1.78690636-0.j
  -0.75655458+0.96566998j]
 [-0.56025834+0.28570964j  0.27579526-0.18182345j  0.14851528+0.88941094j
  -0.19029233+0.40993533j]]

Explanation:

  • Import necessary libraries:
    • Import NumPy and SciPy's fft2 function from the fftpack module.
  • Generate a 2D NumPy array of random numbers:
    • Create a 4x4 array filled with random numbers between 0 and 1.
  • Perform a 2D discrete Fourier transform:
    • Use SciPy's fft2 function to compute the 2D discrete Fourier transform of the array.
  • Print the original array:
    • Display the original 2D array of random numbers.
  • Display the result of the discrete Fourier transform.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Compute Statistical properties of NumPy array with SciPy.
Next: Create Structured array with nested fields in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/perform-2d-discrete-fourier-transform-using-scipys-fftpack.php