Set Options in Problem-Based Approach Using varindex
To set certain options when using the problem-based approach, you must convert problem variables to indices by calling varindex
. For example, the ga
solver accepts an option named InitialPopulationRange
that is a two-row matrix. The first row represents the lower limit and the second row represents the upper limit of the problem variables. The columns of the matrix represent individuals in the population, which are the problem variables. To match the column indices to the problem variables, use varindex
.
For example, set the objective function to the helper function mrosenbrock
, given at the end of this example. This objective function is close to 0 near the point for all . Create 3-D problem variables x
and y
in row form, which is the form ga
expects.
x = optimvar("x",1,3); y = optimvar("y",1,3);
Create an optimization problem with the objective function mrosenbrock(x,y)
.
prob = optimproblem("Objective",mrosenbrock(x,y));
Set the initial range of the x
variables to [-1 2]
, and the range of the y
variables to [0 3]
. To do so, find the indices for the variables.
xidx = varindex(prob,"x")
xidx = 1×3
1 2 3
yidx = varindex(prob,"y")
yidx = 1×3
4 5 6
Set the initial range as a two-row matrix with the first row containing the lower bounds, and the second row containing the upper bounds.
poprange = zeros(2,max([xidx,yidx])); poprange(1,xidx) = -1; poprange(2,xidx) = 2; poprange(1,yidx) = 0; poprange(2,yidx) = 3; disp(poprange)
-1 -1 -1 0 0 0 2 2 2 3 3 3
Set the random number generator, and solve the problem using the initial range matrix.
rng default % For reproducibility opts = optimoptions("ga","InitialPopulationRange",poprange); [sol,fval] = solve(prob,"Solver","ga","Options",opts)
Solving problem using ga. ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
sol = struct with fields:
x: [1.2583 0.7522 1.2317]
y: [1.5830 0.5653 1.5167]
fval = 0.1818
The returned solution has a fairly small objective function value.
Helper Function
This code creates the mrosenbrock
helper function.
function F = mrosenbrock(x,y) F = [10*(y - x.^2),1 - x]; F = sum(F.^2,2); end