In matlab, how to get all edges of a polygon whose indices are labelled by integers using sets

Viewed 62

To put the problem in context: I have a 3D polygon, whose vertices are all labelled by integers 1,...,N, and I have a n*3 matrix faces each of whose rows indicates one of its triangular faces. E.g.

faces =

     1     3     5
     2     4     6
     1     3     6
     2     4     5
     1     4     5
     2     3     6
     1     4     6
     2     3     5

So the first row [1 3 5] denotes the face formed by vertices 1 3 5 and so on. Now I want to get all the edges of these faces.

So I want to use the concept of a set (non-ordered, unique elements). For each row of faces there are three edges, corresponding to three sets, say, {1, 3}, {1, 5}, {3, 5} (here I'm borrowing notations from Python). And I want to create a set of all these sets for all rows. How to do it in Matlab?

In Python it seems I simply can't do a set of sets, since sets are unhashable. In Matlab, it seems everything is a matrix, so I may have to still use a 1x2 matrix to represent each edge, which is fine, but what I want is I don't get duplicated edges. For example, [1 2] and [2 1] are one same edge so I have to make sure one and only one of them is retained in the final dataset.

3 Answers

Here's one way:

  1. create all edges for each triangle (by brute-force)
  2. sort all edges, so that they all "point" in the same direction
  3. select unique ones

Something like this:

faces = [1     3     5
         2     4     6
         1     3     6
         2     4     5
         1     4     5
         2     3     6
         1     4     6
         2     3     5];

% Create all edges
A = [faces(:, [1 2]); faces(:, [2 3]); faces(:, [1 3])];

% First sort(), then unique()
A = unique(sort(A,2), 'rows')

The super quick and easy way is to use the triangulation class and edges method to find them. Given your faces connectivity matrix from above and assuming your vertex data is in vertices:

TR = triangulation(faces, vertices);
edgeMatrix = edges(TR);

And the result:

edgeMatrix =

     1     3
     1     4
     1     5
     1     6
     2     3
     2     4
     2     5
     2     6
     3     5
     3     6
     4     5
     4     6

First search your matrix and extract each vector. After that you can store that in another matrix.

edges =

 1     3 
 3     5
 1     3
 3     4
 5     1
 1     4
 4     4
 4     3

A = unique(edges,'rows')
Related