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.
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) andF_Epoch0
is an M-by-3 matrix of face indices (each row is a set of row indices intoV_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:Then you can take the mean across the columns to get the average X coordinate for each triangular face:
And
meanX
is now a M-by-1 column vector. You can then repeat this for Y and Z coordinates: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:
Check out the documentation for multidimensional arrays to learn more about how this works.