How to calculate the perimeter and area of a polygon?
이전 댓글 표시
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.
채택된 답변
추가 답변 (2개)
Roger Stafford
2014년 3월 23일
0 개 추천
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
2014년 3월 26일
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)));
카테고리
도움말 센터 및 File Exchange에서 Polygonal Shapes에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!