Francesco
Francesco

Reputation: 189

Rearranging array of vertices into array of edges

I have a 3x2 array where each row represents a vertex of a triangle. I would like to reshape it in order to obtain a new array where each row represents a side.

I'm currently trying the following approach:

points = np.array([[0,0], [0,1], [1,0]])

sides = np.array([
    [points[0], points[1]],
    [points[1], points[2]],
    [points[2], points[0]]
])

Is there any build in function to do that in a more elegant way?

Upvotes: 0

Views: 71

Answers (1)

André
André

Reputation: 1068

Elegance is a matter of definition, if you find the following solution more elegant, is up to you. I use np.roll to shift the indices from [0], [1], [2] to [1] [2] [0] and then pair the shifted and unshifted arrays using np.stack, similar to what you do in your manual code (watch the index pairs you create, they are the same).

import numpy as np

points = np.array([[0,0], [0,1], [1,0]])
print(points)
#array([[0, 0],
#       [0, 1],
#       [1, 0]])

sides = np.stack([ 
    points, 
    np.roll(points, -1, axis=-1)
], axis=-1)

print(sides)
#array([[[0, 0],
#        [0, 1]],
#
#       [[0, 1],
#        [1, 0]],
#
#       [[1, 0],
#        [0, 0]]])

Keep in mind that this solution does not work for an arbitrary amount of vertices, but just three.

Upvotes: 2

Related Questions