gpt4 book ai didi

Python:通过迭代加速矩阵坐标映射

转载 作者:行者123 更新时间:2023-11-28 16:45:41 28 4
gpt4 key购买 nike

我试图让这段代码尽可能快地运行,但目前效率很低。

我有一个标量数据的 4D 矩阵。 4 个维度分别对应纬度、经度、高度和时间。数据存储在一个numpy数组中,其形状为(5,5,30,2)。

在 4 个不同的列表中,我为每个轴保留“ map ”,存储每个索引对应的值。例如, map 数组可能如下所示:

mapLatitude = [45.,45.2,45.4,45.6,45.8]
mapLongitude = [-10.8,-10.6,-10.4,-10.2,-10.]
mapAltitude = [0,50,100,150,...,1450]
mapTime = [1345673,1345674]

这意味着在数据矩阵中,位置0,1,3,0的数据点对应于
Lat = 45,Lon = -10.6,Alt = 150,时间 = 1345673。

现在,我需要生成一个新数组,其中包含我的数据矩阵中每个点的坐标。

到目前为止,这是我写的:

import numpy as np

# data = np.array([<all data>])
coordinateMatrix = [
(mapLatitude[index[0]],
mapLongitude[index[1]],
mapAltitude[index[2]],
mapTime[index[3]] ) for index in numpy.ndindex(data.shape) ]

这可行,但需要相当长的时间,尤其是当数据矩阵的大小增加时(我需要将其用于形状类似于 (100,100,150,30) 的矩阵)。

如果有帮助,我需要生成此坐标矩阵以将其提供给 scipy.interpolate.NearestNDInterpolator

有什么关于如何加快速度的建议吗?
非常感谢!

最佳答案

如果你把你的列表变成ndarray,你可以使用广播如下:

coords = np.zeros((5, 5, 30, 2, 4))
coords[..., 0] = np.array(mapLatitude).reshape(5, 1, 1, 1)
coords[..., 1] = np.array(mapLongitude).reshape(1, 5, 1, 1)
coords[..., 2] = np.array(mapAltitude).reshape(1, 1, 30, 1)
coords[..., 3] = np.array(mapTime).reshape(1, 1, 1, 2)

对于更一般的输入,像这样的东西应该可以工作:

def makeCoordinateMatrix(*coords) :
dims = len(coords)
coords = [np.array(a) for a in coords]
shapes = tuple([len(a) for a in coords])
ret = np.zeros(shapes + (dims,))
for j, a in enumerate(coords) :
ret[..., j] = a.reshape((len(a),) + (1,) * (dims - j - 1))
return ret

coordinateMatrix = makeCoordinateMatrix(mapLatitude, mapLongitude,
mapAltitude, mapTime)

关于Python:通过迭代加速矩阵坐标映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14100796/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com