我有一卷实验观察:
import numpy as np
# observations are not uniformly spaced
x = np.random.normal(0, 1, 10)
y = np.random.normal(5, 2, 10)
z = np.random.normal(10, 3, 10)
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
# fake temperatures at those coords
tt = xx*2 + yy*2 + zz*2
# sample distances
dx = np.diff(x)
dy = np.diff(y)
dz = np.diff(z)
grad = np.gradient(tt, [dx, dy, dz]) # returns error
这给了我错误:
ValueError: operands could not be broadcast together with shapes (10,10,10) (3,9) (10,10,10)
.
编辑:根据@jay-kominek 在下面的评论:
np.gradient won't work for you, it simply doesn't handle unevenly sampled data.
我已经更新了问题。有什么函数可以做我的计算吗?
最佳答案
需要注意两点:首先,标量是单个值,而不是数组。其次,函数的签名是 numpy.gradient(f, *varargs, **kwargs)
。请注意 varargs
之前的 *。这意味着如果 varargs
是一个列表,您将传递 *varargs
。或者您可以只提供 varargs
的元素作为单独的参数。
因此,np.gradient
需要沿每个维度的距离的单个值,例如:
np.gradient(tt, np.diff(x)[0], np.diff(y)[0], np.diff(z)[0])
或:
distances = [np.diff(x)[0], np.diff(y)[0], np.diff(z)[0]]
np.gradient(tt, *distances)
关于python - 计算样本位置不均匀的 3D 梯度的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36781698/