How to calculate the perimeter and area of a polygon?

44 views (last 30 days)
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

Roger Stafford
Roger Stafford on 23 Mar 2014
The perimeter looks right, but to make the area right either the first point must equal the last point or you need to extend the p_area by one more term, namely, (x(n)+x(1))*(y(n)-y(1)). Also you need to either ensure that your route around the polygon is clockwise or else you should take the absolute value of the result.
You should note that it is possible to avoid the for-loops here with a vectorized expression for both the perimeter and the area.
  1 Comment
Jason Flint
Jason Flint on 23 Mar 2014
area = 1/2*sum(x.*y([2:end,1])-y.*x([2:end,1]));
Is this what you mean by a vectorised expression?

Sign in to comment.

More Answers (2)

Roger Stafford
Roger Stafford on 23 Mar 2014
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
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 Computational Geometry in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!