w3resource

NumPy: Generate a generic 2D Gaussian-like array

NumPy: Array Object Exercise-79 with Solution

Write a NumPy program to generate a generic 2D Gaussian-like array.

Sample Solution:-

Python Code:

import numpy as np
x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
d = np.sqrt(x*x+y*y)
sigma, mu = 1.0, 0.0
g = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) )
print("2D Gaussian-like array:")
print(g)

Sample Output:

2D Gaussian-like array:                                                                
[[ 0.36787944  0.44822088  0.51979489  0.57375342  0.60279818  0.60279818              
   0.57375342  0.51979489  0.44822088  0.36787944]                                     
 [ 0.44822088  0.54610814  0.63331324  0.69905581  0.73444367  0.73444367              
   0.69905581  0.63331324  0.54610814  0.44822088]                                     
 [ 0.51979489  0.63331324  0.73444367  0.81068432  0.85172308  0.85172308              
   0.81068432  0.73444367  0.63331324  0.51979489]                                     
 [ 0.57375342  0.69905581  0.81068432  0.89483932  0.9401382   0.9401382               
   0.89483932  0.81068432  0.69905581  0.57375342]                                     
 [ 0.60279818  0.73444367  0.85172308  0.9401382   0.98773022  0.98773022              
   0.9401382   0.85172308  0.73444367  0.60279818]                                     
 [ 0.60279818  0.73444367  0.85172308  0.9401382   0.98773022  0.98773022              
   0.9401382   0.85172308  0.73444367  0.60279818]                                     
 [ 0.57375342  0.69905581  0.81068432  0.89483932  0.9401382   0.9401382               
   0.89483932  0.81068432  0.69905581  0.57375342]                                     
 [ 0.51979489  0.63331324  0.73444367  0.81068432  0.85172308  0.85172308              
   0.81068432  0.73444367  0.63331324  0.51979489]                                     
 [ 0.44822088  0.54610814  0.63331324  0.69905581  0.73444367  0.73444367              
   0.69905581  0.63331324  0.54610814  0.44822088]                  
[ 0.36787944  0.44822088  0.51979489  0.57375342  0.60279818  0.60279818              
   0.57375342  0.51979489  0.44822088  0.36787944]]

Python Code Editor:

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

Previous: Write a NumPy program to create a record array from a (flat) list of arrays.
Next: Write a NumPy program to convert a NumPy array into Python list structure.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}