TASK: Write a function that computes the perimeter of a triangle.
COMMENT: Your function should have the form
function p = triangle_perimeter ( x, y )
where x and y are the x and y coordinates of the three vertices,
and p is the length of the perimeter of the triangle. That is,
p is the sum of the lengths of the three triangle sides.
V1--------V3
\ /
\ /
\ /
\/
V2
Suppose we label the vertices 1, 2, and 3. Then the perimeter is
the following sum:
p = sqrt ( ( x1 - x3 )^2 + ( y1 - y3 )^2 )
+ sqrt ( ( x2 - x1 )^2 + ( y2 - y1 )^2 )
+ sqrt ( ( x3 - x2 )^2 + ( y3 - y2 )^2 )
It would be easy to use this formula for the perimeter. But we'd prefer to write it in a way that suggests how to handle a figure with 4 sides, 5 sides, or 100 sides.
The sum seems to be made up by adding 3 terms, of the form
sqrt ( ( x(i) - x(i-1) )^2 + ( y(i) - y(i-1) )^2 )
except that, for the very first step, when i = 1, the index i-1
is illegal. If we can deal with that special case, then we can
compute the perimeter using a FOR loop, and a very similar loop
will work for a shape of any number of sides.
INSTRUCTIONS:
Your function could have the following outline:
Begin with the function header.
Initialize P.
Initialize XOLD and YOLD to be the coordinates of vertex 3.
Open a FOR loop that runs from I = 1 to 3
ADD to P the length of side I, which involves X(I) - XOLD and Y(I) - YOLD.
set XOLD to X(I) and YOLD to Y(I).
end the FOR loop
return
end
CHECK:For the triangle with
xlist = [ 0, 7, 9 ]
ylist = [ 6, 1, 3 ]
the statement
p = triangle_perimeter ( xlist, ylist )
should return a perimeter of about 20.92
SUBMIT: Because it's a function, your file should be named "triangle_perimeter.m". Your file should begin with:
% triangle_perimeter.m
% YOUR NAME
% This script (describe what it does)