%%% How to use the GA algorithm %%% Minimisation of Rosenbrock's function, a common %%% test function for optimizers. %%% The function is a sum of squares %%% The function has a minimum value of zero at the point %%% [1,1]. Because the Rosenbrock's function is quite steep, plot %%% the logarithm of one plus the function. %fsurf(@(x,y) log(1 + 100*(x.^2 - y).^2 + (1 - x).^2),[0,2]) fsurf(@(x,y) 100*(x.^2 - y).^2 + (1 - x).^2,[0,2]) title('1 + 100*(x(1)^2 - x(2))^2 + (1 - x(1))^2') view(-13,78) hold on h1 = plot3(1,1,0.1,'r*','MarkerSize',12); legend(h1,'Minimum','Location','best'); hold off %%% %%% Minimize Using ga %%% %%% To minimize the fitness function using GA, pass %%% a function handle to the fitness function, as %%% well as the number of variables in the problem. %%% To have GA examine the relevant region, include %%% bounds -3 <= x(i) <= 3. %%% Pass the bounds as the fifth and sixth arguments %%% after numberOfVariables. For ga syntax details, %%% see ga. %%% %%% ga is a random algorithm. For reproducibility, %%% set the random number stream. rng default % For reproducibility FitnessFunction = @simple_fitness; numberOfVariables = 2; options = optimoptions('ga','InitialPopulationRange',[1;100],... 'PlotFcn',{@gaplotbestf,@gaplotdistance}); % Include plot functions to monitor the optimization process. options = optimoptions(@ga,'PlotFcn',{@gaplotbestf,@gaplotstopping}); fminuncOptions = optimoptions(@fminunc,'PlotFcn',... {'optimplotfval','optimplotx'}); options = optimoptions(options,'HybridFcn',... {@fminunc, fminuncOptions}); [x,fval] = ga(FitnessFunction,numberOfVariables,[],[],[],[],[],[],... [],options) return %%% %%% Function to be minimised %%% function y = simple_fitness(x) %SIMPLE_FITNESS fitness function for GA y = 100 * (x(1)^2 - x(2)) ^2 + (1 - x(1))^2; end