Main Content

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 variablesxandy, 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")

Figure contains an axes object. The axes object with title rastriginsfcn([x/10,y/10]) contains an object of type functionsurface.

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 variablesxandy. Specify that the variables are bounded by ± 1 0 0 .

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.

Creategaoptions to use thegaplotbestfplot function.

options = optimoptions("ga","PlotFcn","gaplotbestf");

Solve the problem usinggaas 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.

Figure Genetic Algorithm contains an axes object. The axes object with title Best: 1.98992 Mean: 1.98992 contains 2 objects of type line. These objects represent Best fitness, Mean fitness.

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. Becausegais 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.

Figure Genetic Algorithm contains an axes object. The axes object with title Best: 0.994959 Mean: 0.99496 contains 2 objects of type line. These objects represent Best fitness, Mean fitness.

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 bygais not guaranteed to be a global solution.

See Also

||

相关话题