% Used to make the plots for the fmin example % Example 4.8 function [] = optfmin() [xmin, z] = myfmin('myfcn', 0, 0.1, 10); % plot the bracketing process figure(1); hold off; plot(z(:,1), '-'); hold on; plot(z(:,2), ':') plot(z(:,3), '-.') plot(z(:,4), '--') axis([1 15 0 10]) legend('a','t1','t2','c'); xlabel('iteration'); ylabel('x'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % find xmin which minimized J(x) given a abs(b-a)) t1 = b; t2 = b + R*(c-b); else t1 = b - R*(b-a); t2 = b; end J1 = feval(J, t1); J2 = feval(J, t2); z = [a, t1, t2, c]; while (abs(c-a) > tol) if (J2 < J1) a = t1; t1 = t2; t2 = t2 + R*(c - t2); J1 = J2; J2 = feval(J, t2); else c = t2; t2 = t1; t1 = t1 - R*(t1 - a); J2 = J1; J1 = feval(J, t1); end n = n + 1; if (n >= maxit) warning('Maximum numer of iterations reached'); break; end; z = [z; [a, t1, t2, c]]; end %while if (J1 < J2) xmin = t1; else xmin = t2; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This is the function to minimize... function [y] = myfcn(x) y = (x-1).^2 + 1;