Vectorize the Fitness Function
Vectorize for Speed
The genetic algorithm usually runs faster if you vectorize the fitness function. This means that the genetic algorithm only calls the fitness function once, but expects the fitness function to compute the fitness for all individuals in the current population at once. To vectorize the fitness function,
Write the file that computes the function so that it accepts a matrix with arbitrarily many rows, corresponding to the individuals in the population. For example, to vectorize the function
write the file using the following code:
z =x(:,1).^2 - 2*x(:,1).*x(:,2) + 6*x(:,1) + x(:,2).^2 - 6*x(:,2);
The colon in the first entry of
x
indicates all the rows ofx
, so thatx(:, 1)
is a vector. The.^
and.*
operators perform elementwise operations on the vectors.At the command line, set the
UseVectorized
option totrue
usingoptimoptions
.In the Optimize Live Editor task, ensure that the Algorithm settings > Evaluate functions vectorized setting has a check mark.
Note
The fitness function, and any nonlinear constraint function,
must accept an arbitrary number of rows to use the Vectorize option. ga
sometimes
evaluates a single row even during a vectorized calculation.
The following comparison, run at the command line, shows the improvement in speed with
vectorization. The function fun
is a vectorized version of
Rastrigin's function; see Minimize Rastrigin's Function.
fun = @(pop)10.0 * size(pop,2) + sum(pop .^2 - 10.0*cos(2*pi.*pop),2); options = optimoptions('ga','PopulationSize',2000); tic ga(fun,20,[],[],[],[],[],[],[],options); toc
Optimization terminated: maximum number of generations exceeded. Elapsed time is 2.511456 seconds.
options = optimoptions(options,'UseVectorized',true);
tic;
ga(fun,20,[],[],[],[],[],[],[],options);
toc
Optimization terminated: maximum number of generations exceeded. Elapsed time is 1.451496 seconds.
Vectorized Constraints
If there are nonlinear constraints, the objective function and the nonlinear constraints all need to be vectorized in order for the algorithm to compute in a vectorized manner.
Vectorize the Objective and Constraint Functions contains
an example of how to vectorize both for the solver patternsearch
.
The syntax is nearly identical for ga
. The only
difference is that patternsearch
can have its
patterns appear as either row or column vectors; the corresponding
vectors for ga
are the population vectors, which
are always rows.