Calculating the barycenter of multiple triangles

201 views Asked by At

I want to calculate each individual barycenter (centroid) of a list of triangles. Thus far I've managed to write this much :

 function Triangle_Source_Centroid(V_Epoch0, F_Epoch0)


        for i = 1:length(F_Epoch0)


        Centroid_X = F_Epoch0(V_Epoch0(:,1),1)  + F_Epoch0(V_Epoch0(:,1),2)  + F_Epoch0(V_Epoch0(:,1),3);
        Centroid_Y = F_Epoch0(V_Epoch0(:,2),1)  + F_Epoch0(V_Epoch0(:,2),2)  + F_Epoch0(V_Epoch0(:,2),3);
        Centroid_Z = F_Epoch0(V_Epoch0(:,3),1)  + F_Epoch0(V_Epoch0(:,3),2)  + F_Epoch0(V_Epoch0(:,3),3);

        Triangle_Centroid = [Centroid_X; Centroid_Y; Centroid_Z];

        end
end

it doesn't work, and only gives me an error message:

Subscript indices must either be real positive integers or logicals.
1

There are 1 answers

0
gnovice On

Given how the variables are named, I'm guessing that V_Epoch0 is an N-by-3 matrix of vertices (X, Y, and Z for the columns) and F_Epoch0 is an M-by-3 matrix of face indices (each row is a set of row indices into V_Epoch0 showing which points make each triangle). Assuming this is right...

You can actually avoid using a for loop in this case by making use of matrix indexing. For example, to get the X coordinates for every point in F_Epoch0, you can do this:

allX = reshape(V_Epoch0(F_Epoch0, 1), size(F_Epoch0));

Then you can take the mean across the columns to get the average X coordinate for each triangular face:

meanX = mean(allX, 2);

And meanX is now a M-by-1 column vector. You can then repeat this for Y and Z coordinates:

allY = reshape(V_Epoch0(F_Epoch0, 2), size(F_Epoch0));
meanY = mean(allY, 2);
allZ = reshape(V_Epoch0(F_Epoch0, 3), size(F_Epoch0));
meanZ = mean(allZ, 2);
centroids = [meanX meanY meanZ];

And centroids is an M-by-3 matrix of triangle centroid coordinates.

Bonus:

All of the above can actually be done with just this one line:

centroids = squeeze(mean(reshape(V_Epoch0(F_Epoch0, :), [size(F_Epoch0, 1) 3 3]), 2));

Check out the documentation for multidimensional arrays to learn more about how this works.