MATLAB: How to calculate the perimeter and area of a polygon

MATLAB

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.

Best Answer

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.