python - 计算样本位置不均匀的 3D 梯度的函数

标签 python numpy multidimensional-array data-manipulation gradient

我有一卷实验观察:

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/

相关文章:

python - 如何让 python 程序什么都不做?

Python 显示从 1 到 100 的所有质数

python - 遍历一个numpy数组

python - 地 block 上的孵化频率

caching - D中缓存友好的多维数组迭代

python - 盘中数据的每日高/低

python - 给一列多个索引/标题

python-3.x - Python OpenCV - 如何保存 5 channel 图像

java - 从数组中获取索引并将其输出到java中

c - 在C中读取二维char数组