How to calculate the perimeter and area of a polygon?
Show older comments
How would I calculate the perimeter and area of any shape given its coordinates, but without using any built in functions in MATLAB? So far this is what I have:
Perimeter
points = [1 0 ; 3 0 ; 3 2 ; 5 2 ; 5 4 ; 3 4 ; 3 6 ; 1 6 ; 1 4 ; -1 4 ; -1 2 ; 1 2 ;];
perimeter = 0;
for i = 1:size(points, 1)-1
perimeter = perimeter + norm(points(i, :) - points(i+1, :));
end
perimeter = perimeter + norm(points(end, :) - points(1, :)); % Last point to first
fprintf('The perimeter of the polygon is %.3f\n', perimeter)
(points is the set of coordinates)
Area
function p_area = assignment_task_b(x,y)
% Get the number of vertices
n = length(x);
% Initialize the area
p_area = 0;
% Apply the formula
for i = 1 : n-1
p_area = p_area + (x(i) + x(i+1)) * (y(i) - y(i+1));
end
p_area = abs(p_area)/2;
Any feedback and corrections are appreciated.
Accepted Answer
More Answers (2)
Roger Stafford
on 23 Mar 2014
0 votes
Yes, that is what is meant by a "vectorized" expression. However the sign of your area is now the opposite of the sign of your original expression and would be correct only for going counterclockwise. You can take the absolute value to be independent of which way the path goes.
Andrei Bobrov
on 26 Mar 2014
one way
p1 = points(randperm(size(points,1)),:); % Let your data
ii = bsxfun(@minus,p1,mean(p1))*[1;1i];
[~,jj] = sort(angle(ii));
i1 = [ii(jj);ii(jj(1))];
a1 = mod(diff(angle(i1)),2*pi);
v = abs(i2);
area1 = sum(prod([v(1:end-1),v(2:end),sin(a1)]));
perim = sum(abs(diff(i2)));
Categories
Find more on Polygonal Shapes in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!