Custom Output Function for gamultiobj
This example shows how to create a custom output function for gamultiobj
that prints the best objective function values every 20 generations. The vector objective function has three dimensions, and is a function of two variables.
function F = fitnessfcn(x) F = [norm(x)^2,... 0.5*norm(x(:)-[2;-1])^2+2,... 2*norm(x(:)-[-2;-1])^2-1]; end
To monitor the progress of the optimization, create an output function that has the syntax described in Structure of the Output Function. To keep the output reasonably short, print the best (smallest) values found for the three objective functions every 20 generations.
function [state,options,optchanged] = gamextent(options,state,flag) optchanged = false; switch flag case "init" disp("Best function values in each dimension for this generation") case "iter" if mod(state.Generation,20) == 1 % Suppress 95% of iterations. fprintf("Generation %-.0f\n",state.Generation) score = state.Score; nobj = size(score,2); [~,indx] = min(score); % Find indices of minimal objective function values. for i=1:nobj % Print scores for the smallest objective function values % in each dimension. fprintf("%-.3f ",score(indx(i),:)) fprintf("\n") end fprintf("\n") % Blank line before next output end end end
Set options to call the output function, and then run the solver.
opts = optimoptions("gamultiobj",OutputFcn=@gamextent); rng default % For reproducibility x = gamultiobj(@fitnessfcn,2,[],[],[],[],[],[],[],opts);
Best function values in each dimension for this generation Generation 1 2.568 9.068 10.845 4.085 2.078 30.132 3.478 7.478 0.240 Generation 21 0.001 4.446 9.073 5.135 2.001 31.589 4.983 9.955 -0.999 Generation 41 0.000 4.514 9.042 5.020 2.000 31.151 4.983 9.955 -0.999 Generation 61 0.000 4.508 9.061 5.020 2.000 31.151 4.943 9.964 -1.000 Generation 81 0.000 4.494 8.989 5.021 2.000 31.151 4.943 9.964 -1.000 Generation 101 0.000 4.497 9.003 5.017 2.000 31.026 5.003 9.989 -1.000 gamultiobj stopped because the average change in the spread of Pareto solutions is less than options.FunctionTolerance.
As the iterations proceed, the best value of the first objective function approaches 0, the best value of the second objective function approaches 2, and the best value of the third objective function approaches –1. You can see this approach in the main diagonal of each generation.