Minimize Rastrigins' Function Usingga
, Problem-Based
This example shows how to minimize a function with multiple minima using the genetic algorithm in the problem-based approach. For two variablesx
andy
, Rastrigin's function is defined as follows.
ras = @(x, y) 20 + x.^2 + y.^2 - 10*(cos(2*pi*x) + cos(2*pi*y));
在每个方向上绘制缩放10的函数。
rf3 = @(x, y) ras(x/10, y/10); fsurf(rf3,[-30 30],"ShowContours","on") title("rastriginsfcn([x/10,y/10])") xlabel("x") ylabel("y")
The function has many local minima and a global minimum value of 0 that is attained atx
= 0,y
= 0. SeeWhat Is Global Optimization?
Create optimization variablesx
andy
. Specify that the variables are bounded by
.
x = optimvar("x","LowerBound",-100,"UpperBound",100);y = optimvar("y","LowerBound",-100,"UpperBound",100);
Create an optimization problem with the objective functionrastriginsfcn(x)
.
prob = optimproblem("Objective",ras(x,y));
Note:If you have a nonlinear function that is not composed of polynomials, rational expressions, and elementary functions such asexp
, then convert the function to an optimization expression by usingfcn2optimexpr
. SeeConvert Nonlinear Function to Optimization Expressionand万博1manbetx支持操作Optimization Variables and Expressions.
Createga
options to use thegaplotbestf
plot function.
options = optimoptions("ga","PlotFcn","gaplotbestf");
Solve the problem usingga
as the solver.
rngdefault% For reproducibility[sol,fval] = solve(prob,"Solver","ga","Options",options)
Solving problem using ga. Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
sol =struct with fields:x: 0.9950 y: 0.9950
fval = 1.9899
Is the resulting function value the lowest minimum? Perform the search again. Becausega
is a stochastic algorithm, the results can differ.
[sol2,fval2] = solve(prob,"Solver","ga","Options",options)
Solving problem using ga. Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
sol2 =struct with fields:x: 0.9950 y: -4.9289e-06
fval2 = 0.9950
The second solution is better because it has a lower function value. A solution returned byga
is not guaranteed to be a global solution.