我想要画的是从高值到低值的向量。如果代码从以下位置开始:
a = [[1, 8, 9, 10],[2, 15, 3, -1],[3,1,6,11],[13,15,5,-2]]
X,Y = np.meshgrid(np.arange(4), np.arange(4))
U = ?
V = ?从这里开始,我应该设置向量的U和V组件。每个点的大小都是a[x][y]。我不太清楚如何在每个网格点设置U和V使箭头从高到低。
发布于 2013-10-13 00:58:37
这里有一个解决方案(不需要numpy):
import itertools as it
a = [[1, 8, 9, 10],[2, 15, 3, -1],[3,1,6,11],[13,15,5,-2]]
rowSize = len(a[0])
maxVal = a[0][0]
maxIndex = 0
minVal = a[0][0]
minIndex = 0
for k, v in enumerate(it.chain(*a)): # Loop through a flattened list of the values in the array, and locate the indices of the max and min values.
if v > maxVal:
maxVal = v
maxIndex = k
if v < minVal:
minVal = v
minIndex = k
U = (minIndex % rowSize) - (maxIndex % rowSize)
V = (minIndex / rowSize) - (maxIndex / rowSize)
print U, ",", V输出
2 , 2注意,当存在两个相等的最大值时,您还没有定义您想要的行为,就像在您的示例中一样。上面的代码使用“第一”(最左上方)作为真正的最大值,并忽略所有其他代码。
解释:
我将列表扁平化(这意味着我读取的值就像书中的单词一样--首先是第一行,然后是第二行,然后是第三行)。每个值都有一个索引,如下所示:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15例如,第二行和第三列中的值将得到6的索引,因为如果您像一本书一样读取数组,则它是第7个值。
最后,当我们找到最大值或最小值的索引时,我们需要从一维索引中得到2D坐标。因此,我们可以使用mod运算符(%)来获得x值.
例如,6 % 4 = 2,所以X = 2 (第3列)
为了得到Y值,我们使用整数除法运算符(/)。
例如,6 / 4 = 1,所以Y = 1 (第二行)
U和V的公式只是取最大值和最小值的X和Y值,减去它们得到矢量坐标,如下所示:
U = xMin - xMax
V = yMin - yMax如果你想知道,“他为什么不只是使用我刚开始使用的网格解决方案”,有两个原因:第一,如果没有非标准库就能很容易地解决问题,那么使用numpy这样的非标准库通常是不可取的;第二,如果您需要处理大数组,生成一个大型网格可能会导致时间/内存开销增加。
选择最短向量的解决方案:
import itertools as it
a = [[1, 8, 9, 10],[2, 15, 3, -1],[3,1,6,11],[13,15,5,-2]]
rowSize = len(a[0])
values = sorted(enumerate(it.chain(*a)), key=lambda x:x[1]) # Pair each value with its 1D index, then sort the list.
minVal = values[0][1]
maxVal = values[-1][1]
maxIndices = map(lambda x:x[0], filter(lambda x:x[1]==maxVal, values)) # Get a list of all the indices that match the maximum value
minIndices = map(lambda x:x[0], filter(lambda x:x[1]==minVal, values)) # Get a list of all the indices that match the minimum value
def getVector(index1, index2, rowSize): # A function that translates a pair of 1D index values to a "quiver vector"
return ((index1 % rowSize) - (index2 % rowSize), (index1 / rowSize) - (index2 / rowSize))
vectors = [getVector(k2, k1, rowSize) for k1, k2 in it.product(maxIndices, minIndices)] # produce a list of the vectors formed by all possible combinations of the 1D indices for maximum and minimum values
U, V = sorted(vectors, key=lambda x:(x[0]*x[0] + x[1]*x[1])**0.5)[0]
print U, ",", V输出
2 , 0https://stackoverflow.com/questions/19340514
复制相似问题