4

I have a 2D function f(x,y) defined in a (xx,yy) meshgrid. I want to numerically obtain it's partial derivative as shown below. Note that np.gradient doesn't do the job, as it returns a vector field along each of the axes.

enter image description here

How can I do that? Here is my code:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-5, 5, 0.1)
y = np.arange(-4, 4, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
f = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,f)
plt.show()

df=np.gradient(f,y,x) #Doesn't do my job
df=np.array(df)
print(df.shape)

# h = plt.contourf(x,y,df)   #This is what I want to plot.
# plt.show()
Alam
  • 315
  • 5
  • 17

1 Answers1

5

You need to call np.gradient twice:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-5, 5, 0.1)
y = np.arange(-4, 4, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
f = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,f)
plt.show()

dfy = np.gradient(f, y, axis=0)
dfxy = np.gradient(dfy, x, axis=1)
print(dfxy.shape)
# (80, 100)

h = plt.contourf(x, y, dfxy)
plt.show()

Output:

Result

jdehesa
  • 58,456
  • 7
  • 77
  • 121