% This program finds the maximum of the function. % It finds the local maximums, and hopefully finds % the global maximum too. clear x=-2:0.01:2; y1=exp(1./(1+x.^2))+0.1*sin(20*x); plot(x,y1) hold on grid on y=inline('exp(1./(1+x.^2))+0.1*sin(20*x)'); lok_max=[]; for i=1:8 % temp_x=-1.98; temp_x=(floor(100*((4*rand)-2)))/100; temp_y=y(temp_x); t=temp_x; if y(t+0.01) > y(t-0.01) direction = 2; % right elseif y(t+0.01) < y(t-0.01) direction = 1; % left else direction = 0; % flat end if direction ==2 while y(t+0.01) > y(t) t=t+0.01; if t==x(end) break; end x_lokal_max=t; y_lokal_max=y(x_lokal_max); plot(x_lokal_max,y_lokal_max,'r*') pause(0.1) end end if direction ==1 while y(t-0.01) > y(t) t=t-0.01; if t==x(1) break; end x_lokal_max=t; y_lokal_max=y(x_lokal_max); plot(x_lokal_max,y_lokal_max,'r*') pause(0.1) end end lok_max=[lok_max; t y(t)]; end global_max=max(lok_max(:,2)); [p q]=find(lok_max==global_max); max_x=lok_max(p,1); max_y=lok_max(p,2); plot(max_x,max_y,'gs','MarkerFaceColor','g', 'MarkerSize',12)