% P4
close all
% Generate a roughly elliptical random cloud of points.
% There are three parameters to play with: A, N, and NoiseFactor

% Random focii, the center, the separation
F1 = randn(2,1); F2 = randn(2,1); C = (F1+F2)/2; d = norm(F1-F2);

% Choose eccentricity parameter A according to how cigarlike you want 
% the cloud of points: A = 1 (degenerate), A = 1.02 (very),
% A = 1.1 (modest)   A = 3 (quite circular)
A = 1.1; s = A*d;

% Generate an N point elliptical cloud of data
N = 10000; k = 0; P = zeros(2,N);
while k<N
    % Throw a random dart at the center
    Pk = C + s*randn(2,1);
    if norm(F1-Pk) + norm(F2-Pk) <= s
        % Pk inside the random ellipse
        k=k+1; P(:,k) = Pk;
    end
end
% Add noise. 
NoiseFactor = 0.01;
P = P + NoiseFactor*randn(2,N); x = P(1,:)'; y = P(2,:)';

% Take a look at the convex hull. 
idx = convhull(x,y); xConv = x(idx); yConv = y(idx);

% The polygon defined by (xConv(i),yConv(i)) is convex and encloses
% the points (x(i),y(i)).

% Display...

plot(x,y,'.m',F1(1),F1(2),'*k',F2(1),F2(2),'*k',xConv,yConv,'r',xConv,yConv,'or')
axis equal off
title(sprintf('F1 = (%5.2f,%5.2f)    F2 = (%5.2f,%5.2f)     s = %5.2f     n = %1d',...
                   F1,F2,s,length(xConv)),'Fontsize',14)




[A, s, F1x, F1y, F2x, F2y] = EnclosingE(x,y);
nEnclosed = sum( sqrt((x-F1x).^2+(y-F1y).^2) + ...
                 sqrt((x-F2x).^2+(y-F2y).^2) <= s );

% Display the Enclosing Ellipse
h = (F1x+F2x)/2; k = (F1y+F2y)/2; a = s/2;
n = 100; u = linspace(h-a,h+a,n); v = linspace(k-a,k+a,n); Z = zeros(n,n);
for i=1:n
  for j=1:n
     Z(j,i) =  sqrt((u(i)-F1x)^2+(v(j)-F1y)^2) + ...
               sqrt((u(i)-F2x)^2+(v(j)-F2y)^2) - s;   
  end
end
figure
contour(u,v,Z,[0 0],'k')
hold on
plot(x,y,'.m')
plot(F1x,F1y,'ob',F2x,F2y,'ob')
axis equal 
hold off

title(sprintf(...
'Area = %10.4f  s = %8.4f  F1 = (%8.4f,%8.4f)  F2 = (%8.4f,%8.4f) ',...
    A,s,F1x,F1y,F2x,F2y))
xlabel(sprintf('N = %1d    nEnclosed = %1d',N,nEnclosed))
shg


