%
% Application Programming in MatLab-environment
% Autumn 2000
% 
% Exercise 5 & 6
%

% Clear the variables and close all windows
clear
close all

% ----- Problem 1 -----
% See files func1d.m and func2d.m for the definitions
% of the MatLab functions.
h = 0.02;
x = h:h:5;
[f,d] = func1d(x);
hd = plot(x,f,'b-',x,d,'r--');
title('function f');
xlabel('x-coordinate'); ylabel('y-coordinate');
legend([hd(1) ; hd(2)],'function values','derivative');
hold on

% ----- Problem 2 -----
% Minimize function func1d using fmin
tic;
x1 = fmin('func1d',1,3);
t = toc;
plot(x1,func1d(x1),'o');
hold off
fprintf(1,'\nMinimum point and corresponding value: %6.2f %6.2f\n',...
        x1,func1d(x1));
fprintf(1,'\nTime for minimization: %6.2f\n',t);

disp('Press any key to continue.'); pause

% Minimize function func2d using fmins
tic;
x2 = fmins('func2d',[0 0]);
t = toc;
fprintf(1,'\nMinimum point and corresponding value: [ %6.2f %6.2f ] %6.2f\n',x2,func2d(x2));
fprintf(1,'\nTime for minimization: %6.2f\n',t);

disp('Press any key to continue.'); pause

% ----- Problem 3 -----
figure;
[xx,yy] = meshgrid(-0.5:h:1.5);
zz = func2d(xx,yy);
contour(xx,yy,zz,20); hold on
plot(x2(1),x2(2),'o');

[px,py] = gradient(zz,h,h);
grlen = sqrt( px.^2 + py.^2 );
[cm,ci] = min(grlen);
[tm,ri] = min(cm);
plot(xx(ri,ci(ri)),yy(ri,ci(ri)),'*');
fprintf(1,'\nMinimum point for gradient length: [ %6.2f %6.2f ]\n',xx(ri,ci(ri)),yy(ri,ci(ri)));

% ----- Problem 4 -----
% Minimize function func2d using fminunc.
% We set the options vector to display the development of the minimization.
options = optimset('Diagnostics','on','Display','iter','MaxIter',1000);

tic;
[x2,fval] = fminunc('func2d',[0 0],options);
t = toc;
fprintf(1,'\nMinimum point and corresponding value: [ %6.2f %6.2f ] %6.2f\n',x2,fval);
fprintf(1,'\nTime for minimization: %6.2f\n',t);

disp('Press any key to continue.'); pause

% ----- Problem 4 -----
close all
h = 0.01;
x = 0.1:h:4;
[f,d] = func1d(x);
hd = plot(x,f,'b-',x,d,'r--');
title('function f');
xlabel('x-coordinate'); ylabel('y-coordinate');
legend([hd(1) ; hd(2)],'function values','derivative');
hold on

[glob,lok] = extremal(f);
plot(x(lok),f(lok),'*','MarkerSize',12);
plot(x(glob),f(glob),'o','MarkerSize',12);
