function Choosing_f()
% Use fminbnd to find the nearest point on the ellipse

% x(t) = a*cos(t)
% y(t) = b*sin(t) 0<=t<=2pi

% to a given point (alfa,beta). Two different objective functions
% are used.

close all
axis([-6 6 -6 6])
axis square
fill([-6 6 6 -6],[-6 -6 6 6],'k')
hold on
set(gcf,'position',[200 200 600 600])

% Generate and display a random ellipse..
a = 2 + 3*rand(1);
b = 2 + 3*rand(1);
t = linspace(0,2*pi,500);
plot(a*cos(t),b*sin(t),'y','linewidth',2)

% Click in the point (alfa,beta) and display...
title('Click in (alfa,beta)','fontsize',16)
[alfa,beta] = ginput(1);
plot(alfa,beta,'.g','Markersize',30)

% Using MyF1, compute the nearest point and display...

% The search interval [L,R]...
L = 0; R = 2*pi;
[tStar1,MyF1Star] = fminbnd(@(t) MyF1(t,a,b,alfa,beta),L,R);

plot(a*cos(tStar1),b*sin(tStar1),'.m','Markersize',30)
text(-5,-5,'MyF1','color','m','fontsize',16)

% Using MyF2, compute the nearest point and display...

% The search interval [L,R]...
L = 0; R = 2*pi;
[tStar2,MyF2Star] = fminbnd(@(t) MyF2(t,a,b,alfa,beta),L,R);

plot(a*cos(tStar2),b*sin(tStar2),'.c','Markersize',30)
text(4,-5,'MyF2','color','c','fontsize',16)
title(' ')
hold off

% The two objective functions...

function d = MyF1(t,a,b,alfa,beta)
% This is the 1-norm distance between (alfa,beta) and (a*cos(t),b*sin(t))
d = abs(alfa - a*cos(t)) + abs(beta - b*sin(t));

function d = MyF2(t,a,b,alfa,beta)
% This is the 2-norm distance between (alfa,beta) and (a*cos(t),b*sin(t))
d = sqrt((alfa - a*cos(t))^2 + (beta - b*sin(t))^2);