function P4()
% Checks out HConLineSeg on a given function MyF(x,y) defined below.
% It is recommended that you play with the endpoints and try out MyF's of
% your own design.

% The endpoints are (u0,v0) and (u1,v1) where
u0 = 0.7; v0 = 2.1;
u1 = 0.6; v1 = 2.3;
% Encapsulate...
P = cell(2,1)
P{1} = struct('x',u0,'y',v0);
P{2} = struct('x',u1,'y',v1);
% Store the value of MyF and its partial derivatives at these endpoints...
F = cell(2,1);
[MyF0,MyFx0,MyFy0] = MyF(u0,v0);
F{1} = struct('fvalue',MyF0,'fx',MyFx0,'fy',MyFy0);
[MyF1,MyFx1,MyFy1] = MyF(u1,v1);
F{2} = struct('fvalue',MyF1,'fx',MyFx1,'fy',MyFy1);

% Examine error along the line segment
clc
fprintf('tStar |fTrue - fAppx| |fxTrue - fxAppx| |fyTrue - fyAppx|\n')
fprintf('----------------------------------------------------------------------\n')
for tStar = linspace(0,1,11)
[fTrue,fxTrue,fyTrue] = MyF(u0+tStar*(u1-u0),v0+tStar*(v1-v0));
[fAppx,fxAppx,fyAppx] = HConLineSeg(P,F,tStar);
errf = abs(fTrue-fAppx);
errfx = abs(fxTrue-fxAppx);
errfy = abs(fyTrue-fyAppx);
fprintf('%5.1f %10.6f %10.6f %10.6f\n',tStar,errf,errfx,errfy)
end

function [Fval,Fx,Fy] = MyF(x,y)
% Underlying function: f(x,y) = exp(-a(x-x0)^2 - b(y-y0)^2)
% depending on a and b, more nonlinear near (x0,y0). Increasingly flat
% away from this point.
a = .2; b = .6; x0 = 1; y0 = 2;
Fval = exp(-a*(x-1)^2 - b*(y-2)^2);
Fx = -2*a*(x-x0)*Fval;
Fy = -2*b*(y-y0)*Fval;