% 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) % set(gcf,'Position',[50 50 450 350]) hold on grid on y=inline('exp(1./(1+x.^2))+0.1*sin(20*x)'); % lok_max=[]; 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; 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; 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=[t y(t)]; NumberOfRestartsLeft=5; while NumberOfRestartsLeft > 0 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; 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; 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 y_lokal_max <= lok_max(2) NumberOfRestartsLeft = NumberOfRestartsLeft - 1; else lok_max=[t y(t)]; NumberOfRestartsLeft = 5; end 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)