Documentation Center |
On this page… |
---|
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 of x, so that x(:, 1) is a vector. The .^ and .* operators perform elementwise operations on the vectors.
In the User function evaluation pane, set the Evaluate fitness and constraint functions option to vectorized.
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 Vectorize set to On.
options = gaoptimset('PopulationSize',2000); tic;ga(@rastriginsfcn,20,[],[],[],[],[],[],[],options);toc Optimization terminated: maximum number of generations exceeded. Elapsed time is 12.054973 seconds. options=gaoptimset(options,'Vectorize','on'); tic;ga(@rastriginsfcn,20,[],[],[],[],[],[],[],options);toc Optimization terminated: maximum number of generations exceeded. Elapsed time is 1.860655 seconds.
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.