1
我有這個Python腳本應該調整一組三角形元素的座標。該腳本應該將節點的座標從元素改變爲元素的重心。下圖是我對這個問題所作的一個草圖。Python:調整座標
然而什麼是錯在我的劇本,我想不出什麼。座標不會在正確的方向上改變,並且會生成額外的新座標,而我只想調整現有的座標。
有誰知道如何在Python中正確編程?
coords = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 1.0], [1.0, 1.0], [0.0, 2.0], [0.0, 2.0], [1.0, 1.0], [1.0, 2.0], [1.0, 1.0], [2.0, 1.0], [1.0, 2.0], [1.0, 2.0], [2.0, 1.0], [2.0, 2.0], [1.0, 1.0], [2.0, 0.0], [2.0, 1.0], [1.0, 0.0], [2.0, 0.0], [1.0, 1.0]]
elems = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23]]
#define vectors
def add_vectors(*points):
new_x = 0.0
new_y = 0.0
for point in points:
new_x += point[0]
new_y += point[1]
return [new_x, new_y]
def subtract_vectors(a, b):
new_x = a[0] - b[0]
new_y = a[1] - b[1]
return [new_x, new_y]
def mul_by_scalar(vector, scalar):
new_x = vector[0] * scalar
new_y = vector[1] * scalar
return [new_x, new_y]
#define triangles
triangles = []
for elem in elems:
triangles += [coords[e] for e in elem]
#adjust coordinates
CM = mul_by_scalar(add_vectors(*triangles), 1.0/3)
point_to_CM_vectors = []
for point in triangles:
point_to_CM_vectors.append(subtract_vectors(CM, point))
new_triangle = []
for elem in elems:
for point, motion in zip(triangles, point_to_CM_vectors):
new_triangle.append(add_vectors(point, mul_by_scalar(motion, 0.01)))
print 'triangles =', triangles
print 'new_triangle =', new_triangle
在此先感謝您的幫助!
我懷疑'triangles'的值不是你期望的值。事實上,它是'[[0.0,0.0], [1.0,0.0], [0.0,1.0], [0.0,0.0], [1.0,1.0], [0.0,1.0], [0.0 ,1.0], [1.0,1.0], [0.0,2.0], [0.0,2.0], [1.0,1.0], [1.0,2.0], [1.0,1.0], [2.0 1.0], [1.0,2.0], [1.0,2.0], [2.0,1.0], [2.0,2.0], [1.0,1.0], [2.0,0.0], [2.0,1.0 ], [1.0,0.0], [2.0,0.0], [1.0,1.0]]',24個2分的列表。從「三角形」的名稱來看,它應該是別的。無論如何,'CM'不是這些點的重心,如果你檢查它,它是'[7.666666666666666,8.0]'。 –
假設你想讓'triangles'成爲3個座標列表的列表,我會初始化三角形,如下所示:'三角形= [[在elem中爲e的coords [e]]爲elem中的elem]' – mtadd