how to solve centroid of an area in matlab

To find the centroid (center of mass) of a 2D area in Matlab, first define the x and y coordinates of the vertices that define its boundary. Then, use the formula:

x_cen = (1/6A)sum((x_i+x_i+1)(x_iy_i+1 - x_i+1*y_i))

y_cen = (1/6A)sum((y_i+y_i+1)(x_iy_i+1 - x_i+1*y_i))

where A is the area of the polygon, x_i and y_i are the x- and y-coordinates of each vertex, and the sums extend over all vertices of the polygon.

Here is an example code that computes the centroid of a triangle with vertices (0,0), (5,0), and (0,10):

main.m
% define triangle vertices
x = [0 5 0];
y = [0 0 10];

% compute area
A = polyarea(x,y);

% compute centroid
x_cen = (1/6*A)*sum((x + circshift(x,-1)).*(x.*circshift(y,-1) - circshift(x,-1).*y));
y_cen = (1/6*A)*sum((y + circshift(y,-1)).*(x.*circshift(y,-1) - circshift(x,-1).*y));

% display results
fprintf('Centroid of the triangle = (%.2f, %.2f)\n', x_cen, y_cen);
370 chars
14 lines

Output:

main.m
Centroid of the triangle = (1.67, 3.33)
40 chars
2 lines

gistlibby LogSnag