function Eg10_1Rev()
% Generates and displays a random point set and its diameter

% Set up the figure window...
close all
figure
axis([-.2 1.2 -.2 1.2])
hold on

% Generate a random point set...
n = 100; x = rand(n,1); y = rand(n,1);
for i=1:n
P(i) = MakePoint(x(i),y(i));
end

% Compute the diameter and display...
[Q1,Q2] = DiameterPoints(P);
plot([Q1.x Q2.x],[Q1.y Q2.y],'r')
d = GetDist(Q1,Q2);
ShowPointSet(P,'*k')
ShowPointSet([Q1 Q2],'or')
title(sprintf('Diameter = %5.3f',d),'Fontsize',14)
hold off

function P = MakePoint(x,y)
% P is a point with x-coordinate P.x and y-coordinate P.y.
P = struct('x',x,'y',y);

function d = GetDist(P1,P2)
% P1 and P2 are points.
% d is the Euclidean distance between them.
d = sqrt((P1.x - P2.x)^2 + (P1.y - P2.y)^2);

function ShowPointSet(P,s)
% P is a structure array of points.
% s is a string that specifies color, marker type, and line type,
% e.g., 'k', '*b', 'cx--'
% Displays P in the current figure window according to s.
% Assumes hold is on.

for i=1:length(P)
plot(P(i).x,P(i).y,s)
end

function [Q1,Q2] = DiameterPoints(P)
% P is a structure array of points.
% Q1 and Q2 are the points in P with maximum Euclidean separation.

n = length(P);
Q1 = P(1); Q2 = P(2); d = GetDist(Q1,Q2);
for i=1:n-1
for j=i+1:n
% See if P(i) and P(j) are further apart than Q1 and Q2...
dij = GetDist(P(i),P(j));
if dij>d
% A better choice for Q1 and Q2 has been found...
d = dij; Q1 = P(i); Q2 = P(j);
end
end
end