% centroid.m
%
%  The user selects three points that define a triangle.
%  We compute the centroid, display it, and draw lines from the vertices
%  to the centroid.
%
%  Clear the screen.
%
clf
%
%  Get 3 points.
%
fprintf ( 'Select 3 points as vertices of the triangle:' );
grid on
[ ax, ay ] = ginput ( 1 );
[ bx, by ] = ginput ( 1 );
[ cx, cy ] = ginput ( 1 );
%
%  Make lists.
%
xlist = [ ax, bx, cx ];
ylist = [ ay, by, cy ];
%
%  Print the vertices.
%
fprintf ( '\n' );
fprintf ( '  Triangle vertices:\n' );
fprintf ( '\n' );
for i = 1 : 3
  fprintf ( '  %f  %f\n', xlist(i), ylist(i) );
end
%
%  Fill in the triangle with yellow.
%
fill ( xlist, ylist, 'y' );
axis ( [ 0, 1, 0, 1 ] );
%
%  We're going to draw more, so "hold on":
%
hold on
%
%  Draw the triangle with heavy blue lines.
%  Repeat first point at end of list.
%
plot ( [ xlist, ax ], [ ylist, ay ], 'b-', 'LineWidth', 3 );
%
%  Compute the centroid.
%
dx = ( xlist(1) + xlist(2) + xlist(3) ) / 3;
dy = ( ylist(1) + ylist(2) + ylist(3) ) / 3;

fprintf ( '\n' );
fprintf ( '  Centroid: ( %f,%f )\n', dx, dy );
%
%  Draw red lines from each vertex to the centroid.
%
for i = 1 : 3
  plot ( [ xlist(i), dx ], [ ylist(i), dy ], 'r--', 'LineWidth', 3 );
end
%
%  Draw a large black dot at the centroid.
%
plot ( dx, dy, 'k.', 'MarkerSize', 50 );
%
%  We're done drawing.
%
hold off
%
%  Let's save a copy of this plot!
%
print ( '-djpeg', 'centroid.jpg' );


