% 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); % x=-10:0.01:10; % y1=(x-2).*cos(x); x=0:255; y1=sin((pi*x)/256); plot(x,y1) axis([-1 256 0 1.05]) hold on grid on %y=inline('exp(1./(1+x.^2))+0.1*sin(20*x)'); %y=inline('(x-2).*cos(x)'); y=inline('sin((pi*x)/256)'); %temp_x=(floor(100*((20*rand)-10)))/100; %temp_x=(floor(100*((4*rand)-2)))/100; temp_x=floor((256*rand)); temp_y=y(temp_x); t=temp_x; if y(t+1) > y(t-1) direction = 2; % right elseif y(t+1) < y(t-1) direction = 1; % left else direction = 0; % flat end if direction ==2 while y(t+1) > y(t) t=t+1; x_lokal_max=t; y_lokal_max=y(x_lokal_max); plot(x_lokal_max,y_lokal_max,'r*') pause(0.05) end end if direction ==1 while y(t-1) > y(t) t=t-1; x_lokal_max=t; y_lokal_max=y(x_lokal_max); plot(x_lokal_max,y_lokal_max,'r*') pause(0.05) end end