# ga

Find minimum of function using genetic algorithm

## Syntax

``x = ga(fun,nvars)``
``x = ga(fun,nvars,A,b)``
``x = ga(fun,nvars,A,b,Aeq,beq)``
``x = ga(fun,nvars,A,b,Aeq,beq,lb,ub)``
``x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon)``
``x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options)``
``x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon)``
``x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options)``
``x = ga(problem)``
``````[x,fval] = ga(___)``````
``````[x,fval,exitflag,output] = ga(___)``````
``````[x,fval,exitflag,output,population,scores] = ga(___)``````

## Description

example

````x = ga(fun,nvars)` finds a local unconstrained minimum, `x`, to the objective function, `fun`. `nvars` is the dimension (number of design variables) of `fun`. NotePassing Extra Parameters explains how to pass extra parameters to the objective function and nonlinear constraint functions, if necessary. ```

example

````x = ga(fun,nvars,A,b)` finds a local minimum `x` to `fun`, subject to the linear inequalities `A*x` ≤ `b`. `ga` evaluates the matrix product `A*x` as if `x` is transposed (`A*x'`).```

example

````x = ga(fun,nvars,A,b,Aeq,beq)` finds a local minimum `x` to `fun`, subject to the linear equalities `Aeq*x` = `beq` and `A*x` ≤ `b`. (Set `A=[]` and `b=[]` if no linear inequalities exist.) `ga` evaluates the matrix product `Aeq*x` as if `x` is transposed (`Aeq*x'`).```

example

````x = ga(fun,nvars,A,b,Aeq,beq,lb,ub)` defines a set of lower and upper bounds on the design variables, `x`, so that a solution is found in the range `lb `≤` x `≤` ub`. (Set `Aeq=[]` and `beq=[]` if no linear equalities exist.)```

example

````x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon)` subjects the minimization to the constraints defined in `nonlcon`. The function `nonlcon` accepts `x` and returns vectors `C` and `Ceq`, representing the nonlinear inequalities and equalities respectively. `ga` minimizes the `fun` such that `C(x) `≤` 0` and `Ceq(x) = 0`. (Set `lb=[]` and `ub=[]` if no bounds exist.)```

example

````x = ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options)` minimizes with the default optimization parameters replaced by values in `options`. (Set `nonlcon=[]` if no nonlinear constraints exist.) Create `options` using `optimoptions`.```

example

````x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon)` or `x = ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options)` requires that the variables listed in `IntCon` take integer values. NoteWhen there are integer constraints, `ga` does not accept linear or nonlinear equality constraints, only inequality constraints. ```
````x = ga(problem)` finds the minimum for `problem`, a structure described in `problem`.```

example

``````[x,fval] = ga(___)```, for any previous input arguments, also returns `fval`, the value of the fitness function at `x`.```

example

``````[x,fval,exitflag,output] = ga(___)``` also returns `exitflag`, an integer identifying the reason the algorithm terminated, and `output`, a structure that contains output from each generation and other information about the performance of the algorithm.```

example

``````[x,fval,exitflag,output,population,scores] = ga(___)``` also returns a matrix `population`, whose rows are the final population, and a vector `scores`, the scores of the final population.```

## Examples

collapse all

The `ps_example.m` file ships with your software. Plot the function.

```xi = linspace(-6,2,300); yi = linspace(-4,4,300); [X,Y] = meshgrid(xi,yi); Z = ps_example([X(:),Y(:)]); Z = reshape(Z,size(X)); surf(X,Y,Z,'MeshStyle','none') colormap 'jet' view(-26,43) xlabel('x(1)') ylabel('x(2)') title('ps\_example(x)')```

Find the minimum of this function using `ga`.

```rng default % For reproducibility x = ga(@ps_example,2)```
```Optimization terminated: average change in the fitness value less than options.FunctionTolerance. ```
```x = 1×2 -4.6793 -0.0860 ```

Use the genetic algorithm to minimize the `ps_example` function on the region `x(1) + x(2) >= 1` and `x(2) <= 5 + x(1)`.

First, convert the two inequality constraints to the matrix form `A*x <= b`. In other words, get the `x` variables on the left-hand side of the inequality, and make both inequalities less than or equal:

`-x(1) -x(2) <= -1`

`-x(1) + x(2) <= 5`

```A = [-1,-1; -1,1]; b = [-1;5];```

Solve the constrained problem using `ga`.

```rng default % For reproducibility fun = @ps_example; x = ga(fun,2,A,b)```
```Optimization terminated: average change in the fitness value less than options.FunctionTolerance. ```
```x = 1×2 0.9991 0.0000 ```

The constraints are satisfied to within the default value of the constraint tolerance, `1e-3`. To see this, compute `A*x' - b`, which should have negative components.

`disp(A*x' - b)`
``` 0.0009 -5.9991 ```

Use the genetic algorithm to minimize the `ps_example` function on the region `x(1) + x(2) >= 1` and `x(2) == 5 + x(1)`.

First, convert the two constraints to the matrix form `A*x <= b` and `Aeq*x = beq`. In other words, get the `x` variables on the left-hand side of the expressions, and make the inequality into less than or equal form:

`-x(1) -x(2) <= -1`

`-x(1) + x(2) == 5`

```A = [-1 -1]; b = -1; Aeq = [-1 1]; beq = 5;```

Solve the constrained problem using `ga`.

```rng default % For reproducibility fun = @ps_example; x = ga(fun,2,A,b,Aeq,beq)```
```Optimization terminated: average change in the fitness value less than options.FunctionTolerance. ```
```x = 1×2 -2.0000 2.9990 ```

Check that the constraints are satisfied to within the default value of `ConstraintTolerance`, `1e-3`.

`disp(A*x' - b)`
``` 9.9998e-04 ```
`disp(Aeq*x' - beq)`
``` -9.9937e-04 ```

Use the genetic algorithm to minimize the `ps_example` function on the region `x(1) + x(2) >= 1` and `x(2) == 5 + x(1)`. In addition, set bounds `1 <= x(1) <= 6` and `-3 <= x(2) <= 8`.

First, convert the two linear constraints to the matrix form `A*x <= b` and `Aeq*x = beq`. In other words, get the `x` variables on the left-hand side of the expressions, and make the inequality into less than or equal form:

`-x(1) -x(2) <= -1`

`-x(1) + x(2) == 5`

```A = [-1 -1]; b = -1; Aeq = [-1 1]; beq = 5;```

Set bounds `lb` and `ub`.

```lb = [1 -3]; ub = [6 8];```

Solve the constrained problem using `ga`.

```rng default % For reproducibility fun = @ps_example; x = ga(fun,2,A,b,Aeq,beq,lb,ub)```
```Optimization terminated: average change in the fitness value less than options.FunctionTolerance. ```
```x = 1×2 1.0000 5.9991 ```

Check that the linear constraints are satisfied to within the default value of `ConstraintTolerance`, `1e-3`.

`disp(A*x' - b)`
``` -5.9991 ```
`disp(Aeq*x' - beq)`
``` -9.0713e-04 ```

Use the genetic algorithm to minimize the `ps_example` function on the region $2{\mathit{x}}_{1}^{2}+{\mathit{x}}_{2}^{2}\le 3$ and $\left({x}_{1}+1{\right)}^{2}=\left({x}_{2}/2{\right)}^{4}$.

To do so, first write a function `ellipsecons.m` that returns the inequality constraint in the first output, `c`, and the equality constraint in the second output, `ceq`. Save the file `ellipsecons.m` to a folder on your MATLAB® path.

`type ellipsecons`
```function [c,ceq] = ellipsecons(x) c = 2*x(1)^2 + x(2)^2 - 3; ceq = (x(1)+1)^2 - (x(2)/2)^4; ```

Include a function handle to `ellipsecons` as the `nonlcon` argument.

```nonlcon = @ellipsecons; fun = @ps_example; rng default % For reproducibility x = ga(fun,2,[],[],[],[],[],[],nonlcon)```
```Optimization terminated: average change in the fitness value less than options.FunctionTolerance and constraint violation is less than options.ConstraintTolerance. ```
```x = 1×2 -0.9766 0.0362 ```

Check that the nonlinear constraints are satisfied at `x`. The constraints are satisfied when `c` ≤ 0 and `ceq` = 0 to within the default value of `ConstraintTolerance`, `1e-3`.

`[c,ceq] = nonlcon(x)`
```c = -1.0911 ```
```ceq = 5.4645e-04 ```

Use the genetic algorithm to minimize the `ps_example` function on the region `x(1) + x(2) >= 1` and `x(2) == 5 + x(1)` using a constraint tolerance that is smaller than the default.

First, convert the two constraints to the matrix form `A*x <= b` and `Aeq*x = beq`. In other words, get the `x` variables on the left-hand side of the expressions, and make the inequality into less than or equal form:

`-x(1) -x(2) <= -1`

`-x(1) + x(2) == 5`

```A = [-1 -1]; b = -1; Aeq = [-1 1]; beq = 5;```

To obtain a more accurate solution, set a constraint tolerance of `1e-6`. And to monitor the solver progress, set a plot function.

`options = optimoptions('ga','ConstraintTolerance',1e-6,'PlotFcn', @gaplotbestf);`

Solve the minimization problem.

```rng default % For reproducibility fun = @ps_example; x = ga(fun,2,A,b,Aeq,beq,[],[],[],options)```
```Optimization terminated: average change in the fitness value less than options.FunctionTolerance. ```

```x = 1×2 -2.0000 3.0000 ```

Check that the linear constraints are satisfied to within `1e-6`.

`disp(A*x' - b)`
``` 9.9999e-07 ```
`disp(Aeq*x' - beq)`
``` -9.9503e-07 ```

Use the genetic algorithm to minimize the `ps_example` function subject to the constraint that `x(1)` is an integer.

```IntCon = 1; rng default % For reproducibility fun = @ps_example; A = []; b = []; Aeq = []; beq = []; lb = []; ub = []; nonlcon = []; x = ga(fun,2,A,b,Aeq,beq,lb,ub,nonlcon,IntCon)```
```Optimization terminated: average change in the penalty fitness value less than options.FunctionTolerance and constraint violation is less than options.ConstraintTolerance. ```
```x = 1×2 -5.0000 -0.0000 ```

Use to genetic algorithm to minimize an integer-constrained nonlinear problem. Obtain both the location of the minimum and the minimum function value.

```IntCon = 1; rng default % For reproducibility fun = @ps_example; A = []; b = []; Aeq = []; beq = []; lb = []; ub = []; nonlcon = []; [x,fval] = ga(fun,2,A,b,Aeq,beq,lb,ub,nonlcon,IntCon)```
```Optimization terminated: average change in the penalty fitness value less than options.FunctionTolerance and constraint violation is less than options.ConstraintTolerance. ```
```x = 1×2 -5.0000 -0.0000 ```
```fval = -1.9178 ```

Compare this result to the solution of the problem with no constraints.

`[x,fval] = ga(fun,2)`
```Optimization terminated: maximum number of generations exceeded. ```
```x = 1×2 -4.7121 0.0051 ```
```fval = -1.9949 ```

Use the genetic algorithm to minimize the `ps_example` function constrained to have `x(1)` integer-valued. To understand the reason the solver stopped and how `ga` searched for a minimum, obtain the `exitflag` and `output` results. Also, plot the minimum observed objective function value as the solver progresses.

```IntCon = 1; rng default % For reproducibility fun = @ps_example; A = []; b = []; Aeq = []; beq = []; lb = []; ub = []; nonlcon = []; options = optimoptions('ga','PlotFcn', @gaplotbestf); [x,fval,exitflag,output] = ga(fun,2,A,b,Aeq,beq,lb,ub,nonlcon,IntCon,options)```

```Optimization terminated: average change in the penalty fitness value less than options.FunctionTolerance and constraint violation is less than options.ConstraintTolerance. ```
```x = 1×2 -5.0000 -0.0000 ```
```fval = -1.9178 ```
```exitflag = 1 ```
```output = struct with fields: problemtype: 'integerconstraints' rngstate: [1x1 struct] generations: 96 funccount: 3691 message: 'Optimization terminated: average change in the penalty fitness value less than options.FunctionTolerance...' maxconstraint: 0 hybridflag: [] ```

Use the genetic algorithm to minimize the `ps_example` function constrained to have `x(1)` integer-valued. Obtain all outputs, including the final population and vector of scores.

```IntCon = 1; rng default % For reproducibility fun = @ps_example; A = []; b = []; Aeq = []; beq = []; lb = []; ub = []; nonlcon = []; [x,fval,exitflag,output,population,scores] = ga(fun,2,A,b,Aeq,beq,lb,ub,nonlcon,IntCon);```
```Optimization terminated: average change in the penalty fitness value less than options.FunctionTolerance and constraint violation is less than options.ConstraintTolerance. ```

Examine the first 10 members of the final population and their corresponding scores. Notice that `x(1)` is integer-valued for all these population members. The integer `ga` algorithm generates only integer-feasible populations.

`disp(population(1:10,:))`
``` -5.0000 -0.0000 -5.0000 -0.0000 -5.0000 0.0014 -6.0000 0.0008 -13.0000 -0.0124 -10.0000 0.0011 -4.0000 -0.0010 0 0.0072 -4.0000 0.0010 -5.0000 -0.0000 ```
`disp(scores(1:10))`
``` -1.9178 -1.9178 -1.9165 1.0008 64.0124 25.0011 -1.5126 2.5072 -1.5126 -1.9178 ```

## Input Arguments

collapse all

Objective function, specified as a function handle or function name. Write the objective function to accept a row vector of length `nvars` and return a scalar value.

When the `'UseVectorized'` option is `true`, write `fun` to accept a `pop`-by-`nvars` matrix, where `pop` is the current population size. In this case, `fun` returns a vector the same length as `pop` containing the fitness function values. Ensure that `fun` does not assume any particular size for `pop`, since `ga` can pass a single member of a population even in a vectorized calculation.

Example: `fun = @(x)(x-[4,2]).^2`

Data Types: `char` | `function_handle` | `string`

Number of variables, specified as a positive integer. The solver passes row vectors of length `nvars` to `fun`.

Example: `4`

Data Types: `double`

Linear inequality constraints, specified as a real matrix. `A` is an `M`-by-`nvars` matrix, where `M` is the number of inequalities.

`A` encodes the `M` linear inequalities

`A*x <= b`,

where `x` is the column vector of `nvars` variables `x(:)`, and `b` is a column vector with `M` elements.

For example, to specify

x1 + 2x2 ≤ 10
3x1 + 4x2 ≤ 20
5x1 + 6x2 ≤ 30,

give these constraints:

```A = [1,2;3,4;5,6]; b = [10;20;30];```

Example: To specify that the control variables sum to 1 or less, give the constraints `A = ones(1,N)` and `b = 1`.

Data Types: `double`

Linear inequality constraints, specified as a real vector. `b` is an `M`-element vector related to the `A` matrix. If you pass `b` as a row vector, solvers internally convert `b` to the column vector `b(:)`.

`b` encodes the `M` linear inequalities

`A*x <= b`,

where `x` is the column vector of `N` variables `x(:)`, and `A` is a matrix of size `M`-by-`N`.

For example, to specify

x1 + 2x2 ≤ 10
3x1 + 4x2 ≤ 20
5x1 + 6x2 ≤ 30,

give these constraints:

```A = [1,2;3,4;5,6]; b = [10;20;30];```

Example: To specify that the control variables sum to 1 or less, give the constraints `A = ones(1,N)` and `b = 1`.

Data Types: `double`

Linear equality constraints, specified as a real matrix. `Aeq` is an `Me`-by-`nvars` matrix, where `Me` is the number of equalities.

`Aeq` encodes the `Me` linear equalities

`Aeq*x = beq`,

where `x` is the column vector of `N` variables `x(:)`, and `beq` is a column vector with `Me` elements.

For example, to specify

x1 + 2x2 + 3x3 = 10
2x1 + 4x2 + x3 = 20,

give these constraints:

```Aeq = [1,2,3;2,4,1]; beq = [10;20];```

Example: To specify that the control variables sum to 1, give the constraints ```Aeq = ones(1,N)``` and `beq = 1`.

Data Types: `double`

Linear equality constraints, specified as a real vector. `beq` is an `Me`-element vector related to the `Aeq` matrix. If you pass `beq` as a row vector, solvers internally convert `beq` to the column vector `beq(:)`.

`beq` encodes the `Me` linear equalities

`Aeq*x = beq`,

where `x` is the column vector of `N` variables `x(:)`, and `Aeq` is a matrix of size `Meq`-by-`N`.

For example, to specify

x1 + 2x2 + 3x3 = 10
2x1 + 4x2 + x3 = 20,

give these constraints:

```Aeq = [1,2,3;2,4,1]; beq = [10;20];```

Example: To specify that the control variables sum to 1, give the constraints ```Aeq = ones(1,N)``` and `beq = 1`.

Data Types: `double`

Lower bounds, specified as a real vector or array of doubles. `lb` represents the lower bounds element-wise in `lb `` x `` ub`.

Internally, `ga` converts an array `lb` to the vector `lb(:)`.

Example: `lb = [0;-Inf;4]` means `x(1) ≥ 0`, `x(3) ≥ 4`.

Data Types: `double`

Upper bounds, specified as a real vector or array of doubles. `ub` represents the upper bounds element-wise in `lb `` x `` ub`.

Internally, `ga` converts an array `ub` to the vector `ub(:)`.

Example: `ub = [Inf;4;10]` means `x(2) ≤ 4`, `x(3) ≤ 10`.

Data Types: `double`

Nonlinear constraints, specified as a function handle or function name. `nonlcon` is a function that accepts a vector or array `x` and returns two arrays, `c(x)` and `ceq(x)`.

• `c(x)` is the array of nonlinear inequality constraints at `x`. `ga` attempts to satisfy

`c(x) <= 0`

for all entries of `c`.

• `ceq(x)` is the array of nonlinear equality constraints at `x`. `ga` attempts to satisfy

`ceq(x) = 0`

for all entries of `ceq`.

For example,

`x = ga(@myfun,4,A,b,Aeq,beq,lb,ub,@mycon)`

where `mycon` is a MATLAB® function such as

```function [c,ceq] = mycon(x) c = ... % Compute nonlinear inequalities at x. ceq = ... % Compute nonlinear equalities at x.```

To learn how to use vectorized constraints, see Vectorized Constraints.

Note

`ga` does not enforce nonlinear constraints to be satisfied when the `PopulationType` option is set to `'bitString'` or `'custom'`.

If `IntCon` is not empty, the second output of `nonlcon` (`ceq`) must be an empty entry (`[]`).

For information on how `ga` uses `nonlcon`, see Nonlinear Constraint Solver Algorithms.

Data Types: `char` | `function_handle` | `string`

Optimization options, specified as the output of `optimoptions` or a structure.

`optimoptions` hides the options listed in italics. See Options that optimoptions Hides.

• Values in `{}` denote the default value.

• `{}*` represents the default when there are linear constraints, and for `MutationFcn` also when there are bounds.

• I* indicates that `ga` handles options for integer constraints differently; this notation does not apply to `gamultiobj`.

• NM indicates that the option does not apply to `gamultiobj`.

Options for `ga`, Integer `ga`, and `gamultiobj`

OptionDescriptionValues
`ConstraintTolerance`

Determines the feasibility with respect to nonlinear constraints. Also, `max(sqrt(eps),ConstraintTolerance)` determines feasibility with respect to linear constraints.

For an options structure, use `TolCon`.

Positive scalar | `{1e-3}`

`CreationFcn`

I* Function that creates the initial population. Specify as a name of a built-in creation function or a function handle. See Population Options.

`{'gacreationuniform'}` | `{'gacreationlinearfeasible'}*` | Custom creation function

`CrossoverFcn`

I* Function that the algorithm uses to create crossover children. Specify as a name of a built-in crossover function or a function handle. See Crossover Options.

`{'crossoverscattered'}` for `ga`, `{'crossoverintermediate'}*` for `gamultiobj` | `'crossoverheuristic'` | `'crossoversinglepoint'` | `'crossovertwopoint'` | `'crossoverarithmetic'` | Custom crossover function

`CrossoverFraction`

The fraction of the population at the next generation, not including elite children, that the crossover function creates.

Positive scalar | `{0.8}`

`Display`

Level of display.

`'off'` | `'iter'` | `'diagnose'` | `{'final'}`

`DistanceMeasureFcn`

Function that computes distance measure of individuals. Specify as a name of a built-in distance measure function or a function handle. The value applies to decision variable or design space (genotype) or to function space (phenotype). The default `'distancecrowding'` is in function space (phenotype). For `gamultiobj` only. See Multiobjective Options.

For an options structure, use a function handle, not a name.

`{'distancecrowding'}` means the same as `{@distancecrowding,'phenotype'}` | `{@distancecrowding,'genotype'}` | Custom distance function

`EliteCount`

NM Positive integer specifying how many individuals in the current generation are guaranteed to survive to the next generation. Not used in `gamultiobj`.

Positive integer | `{ceil(0.05*PopulationSize)}` | ```{0.05*(default PopulationSize)}``` for mixed-integer problems

`FitnessLimit`

NM If the fitness function attains the value of `FitnessLimit`, the algorithm halts.

Scalar | `{-Inf}`

`FitnessScalingFcn`

Function that scales the values of the fitness function. Specify as a name of a built-in scaling function or a function handle. Option unavailable for `gamultiobj`.

`{'fitscalingrank'}` | `'fitscalingshiftlinear'` | `'fitscalingprop'` | `'fitscalingtop'` | Custom fitness scaling function

`FunctionTolerance`

The algorithm stops if the average relative change in the best fitness function value over `MaxStallGenerations` generations is less than or equal to `FunctionTolerance`. If `StallTest` is `'geometricWeighted'`, then the algorithm stops if the weighted average relative change is less than or equal to `FunctionTolerance`.

For `gamultiobj`, the algorithm stops when the geometric average of the relative change in value of the spread over `options.MaxStallGenerations` generations is less than `options.FunctionTolerance`, and the final spread is less than the mean spread over the past `options.MaxStallGenerations` generations. See gamultiobj Algorithm.

For an options structure, use `TolFun`.

Positive scalar | `{1e-6}` for `ga`, `{1e-4}` for `gamultiobj`

`HybridFcn`

I* Function that continues the optimization after `ga` terminates. Specify as a name or a function handle.

Alternatively, a cell array specifying the hybrid function and its options. See ga Hybrid Function.

For `gamultiobj`, the only hybrid function is `@fgoalattain`. See gamultiobj Hybrid Function.

Function name or handle | ```'fminsearch' | 'patternsearch' | 'fminunc' | 'fmincon' | {[]}```

or

1-by-2 cell array | `{@solver, hybridoptions}`, where ```solver = fminsearch```, `patternsearch`, `fminunc`, or `fmincon` `{[]}`

InitialPenalty

NM I* Initial value of penalty parameter

Positive scalar | `{10}`

`InitialPopulationMatrix`

Initial population used to seed the genetic algorithm. Has up to `PopulationSize` rows and `N` columns, where `N` is the number of variables. You can pass a partial population, meaning one with fewer than `PopulationSize` rows. In that case, the genetic algorithm uses `CreationFcn` to generate the remaining population members. See Population Options

For an options structure, use `InitialPopulation`.

Matrix | `{[]}`

`InitialPopulationRange`

Matrix or vector specifying the range of the individuals in the initial population. Applies to `gacreationuniform` creation function. `ga` shifts and scales the default initial range to match any finite bounds.

For an options structure, use `PopInitRange`.

Matrix or vector | `{[-10;10]}` for unbounded components, `{[-1e4+1;1e4+1]}` for unbounded components of integer-constrained problems, `{[lb;ub]}` for bounded components, with the default range modified to match one-sided bounds.

`InitialScoresMatrix`

I* Initial scores used to determine fitness. Has up to `PopulationSize` rows and has `Nf` columns, where `Nf` is the number of fitness functions (`1` for `ga`, greater than `1` for `gamultiobj`). You can pass a partial scores matrix, meaning one with fewer than `PopulationSize` rows. In that case, the solver fills in the scores when it evaluates the fitness functions.

For an options structure, use `InitialScores`.

Column vector for single objective | matrix for multiobjective | `{[]}`

`MaxGenerations`

Maximum number of iterations before the algorithm halts.

For an options structure, use `Generations`.

Positive integer |`{100*numberOfVariables}` for `ga`, `{200*numberOfVariables}` for `gamultiobj`

`MaxStallGenerations`

The algorithm stops if the average relative change in the best fitness function value over `MaxStallGenerations` generations is less than or equal to `FunctionTolerance`. If `StallTest` is `'geometricWeighted'`, then the algorithm stops if the weighted average relative change is less than or equal to `FunctionTolerance`.

For `gamultiobj`, the algorithm stops when the geometric average of the relative change in value of the spread over `options.MaxStallGenerations` generations is less than `options.FunctionTolerance`, and the final spread is less than the mean spread over the past `options.MaxStallGenerations` generations. See gamultiobj Algorithm.

For an options structure, use `StallGenLimit`.

Positive integer | `{50}` for `ga`, `{100}` for `gamultiobj`

`MaxStallTime`

NM The algorithm stops if there is no improvement in the objective function for `MaxStallTime` seconds, as measured by `tic` and `toc`.

For an options structure, use `StallTimeLimit`.

Positive scalar `| {Inf}`

`MaxTime`

The algorithm stops after running after `MaxTime` seconds, as measured by `tic` and `toc`. This limit is enforced after each iteration, so `ga` can exceed the limit when an iteration takes substantial time.

For an options structure, use `TimeLimit`.

Positive scalar | `{Inf}`

MigrationDirection

Direction of migration. See Migration Options

`'both'` | `{'forward'}`

MigrationFraction

Scalar from 0 through 1 specifying the fraction of individuals in each subpopulation that migrates to a different subpopulation. See Migration Options

Scalar | `{0.2}`

MigrationInterval

Positive integer specifying the number of generations that take place between migrations of individuals between subpopulations. See Migration Options.

Positive integer | `{20}`

`MutationFcn`

I* Function that produces mutation children. Specify as a name of a built-in mutation function or a function handle. See Mutation Options.

`{'mutationgaussian'}` for `ga`, `{'mutationadaptfeasible'}*` for `gamultiobj` | `'mutationuniform'` | Custom mutation function

`NonlinearConstraintAlgorithm`

Nonlinear constraint algorithm. See Nonlinear Constraint Solver Algorithms. Option unchangeable for `gamultiobj`.

For an options structure, use `NonlinConAlgorithm`.

`{'auglag'}` for `ga`, `{'penalty'}` for `gamultiobj`

`OutputFcn`

Functions that `ga` calls at each iteration. Specify as a function handle or a cell array of function handles. See Output Function Options.

For an options structure, use `OutputFcns`.

Function handle or cell array of function handles | `{[]}`

`ParetoFraction`

Scalar from 0 through 1 specifying the fraction of individuals to keep on the first Pareto front while the solver selects individuals from higher fronts, for `gamultiobj` only. See Multiobjective Options.

Scalar | `{0.35}`

PenaltyFactor

NM I* Penalty update parameter.

Positive scalar | `{100}`

`PlotFcn`

Function that plots data computed by the algorithm. Specify as a name of a built-in plot function, a function handle, or a cell array of built-in names or function handles. See Plot Options.

For an options structure, use `PlotFcns`.

`ga` or `gamultiobj`: ```{[]} | 'gaplotdistance' | 'gaplotgenealogy' | 'gaplotselection' | 'gaplotscorediversity' |'gaplotscores' | 'gaplotstopping' | 'gaplotmaxconstr' | ```Custom plot function

`ga` only: ```'gaplotbestf' | 'gaplotbestindiv' | 'gaplotexpectation' | 'gaplotrange'```

`gamultiobj` only: ```'gaplotpareto' | 'gaplotparetodistance' | 'gaplotrankhist' | 'gaplotspread'```

PlotInterval

Positive integer specifying the number of generations between consecutive calls to the plot functions.

Positive integer | `{1}`

`PopulationSize`

Size of the population.

Positive integer | `{50}` when ```numberOfVariables <= 5```, `{200}` otherwise | `{min(max(10*nvars,40),100)}` for mixed-integer problems

`PopulationType`

Data type of the population. Must be `'doubleVector'` for mixed integer problems.

`'bitstring'` | `'custom'` | `{'doubleVector'}`

`ga` ignores all constraints when `PopulationType` is set to `'bitString'` or `'custom'`. See Population Options.

`SelectionFcn`

I* Function that selects parents of crossover and mutation children. Specify as a name of a built-in selection function or a function handle.

`gamultiobj` uses only `'selectiontournament'`.

`{'selectionstochunif'}` for `ga`, `{'selectiontournament'}` for `gamultiobj` | `'selectionremainder'` | `'selectionuniform'` | `'selectionroulette'` | Custom selection function

StallTest

NM Stopping test type.

`'geometricWeighted'` | `{'averageChange'}`

`UseParallel`

Compute fitness and nonlinear constraint functions in parallel. See Vectorize and Parallel Options (User Function Evaluation) and How to Use Parallel Processing in Global Optimization Toolbox.

`true` | `{false}`

`UseVectorized`

Specifies whether functions are vectorized. See Vectorize and Parallel Options (User Function Evaluation) and Vectorize the Fitness Function.

For an options structure, use `Vectorized` with the values `'on'` or `'off'`.

`true` | `{false}`

Example: `optimoptions('ga','PlotFcn',@gaplotbestf)`

Integer variables, specified as a vector of positive integers taking values from `1` to `nvars`. Each value in `IntCon` represents an `x` component that is integer-valued.

Note

When `IntCon` is nonempty, `Aeq` and `beq` must be an empty entry (`[]`), and `nonlcon` must return empty for `ceq`. For more information on integer programming, see Mixed Integer ga Optimization.

Example: To specify that the even entries in `x` are integer-valued, set `IntCon` to `2:2:nvars`

Data Types: `double`

Problem description, specified as a structure containing these fields.

 `fitnessfcn` Fitness functions `nvars` Number of design variables `Aineq` `A` matrix for linear inequality constraints `Bineq` `b` vector for linear inequality constraints `Aeq` `Aeq` matrix for linear equality constraints `Beq` `beq` vector for linear equality constraints `lb` Lower bound on `x` `ub` Upper bound on `x` `nonlcon` Nonlinear constraint function `rngstate` Optional field to reset the state of the random number generator `solver` `'ga'` `options` Options created using `optimoptions` or an options structure

Data Types: `struct`

## Output Arguments

collapse all

Solution, returned as a real vector. `x` is the best point that `ga` located during its iterations.

Objective function value at the solution, returned as a real number. Generally, `fval` = `fun(x)`.

Reason that `ga` stopped, returned as an integer.

Exit FlagMeaning
`1`

Without nonlinear constraints — Average cumulative change in value of the fitness function over `MaxStallGenerations` generations is less than `FunctionTolerance`, and the constraint violation is less than `ConstraintTolerance`.

With nonlinear constraints — Magnitude of the complementarity measure (see Complementarity Measure) is less than `sqrt(ConstraintTolerance)`, the subproblem is solved using a tolerance less than `FunctionTolerance`, and the constraint violation is less than `ConstraintTolerance`.

`3`

Value of the fitness function did not change in `MaxStallGenerations` generations and the constraint violation is less than `ConstraintTolerance`.

`4`

Magnitude of step smaller than machine precision and the constraint violation is less than `ConstraintTolerance`.

`5`

Minimum fitness limit `FitnessLimit` reached and the constraint violation is less than `ConstraintTolerance`.

`0`

Maximum number of generations `MaxGenerations` exceeded.

`-1`

Optimization terminated by an output function or plot function.

`-2`

No feasible point found.

`-4`

Stall time limit `MaxStallTime` exceeded.

`-5`

Time limit `MaxTime` exceeded.

When there are integer constraints, `ga` uses the penalty fitness value instead of the fitness value for stopping criteria.

Information about the optimization process, returned as a structure with these fields:

• `problemtype` — Problem type, one of:

• `'unconstrained'`

• `'boundconstraints'`

• `'linearconstraints'`

• `'nonlinearconstr'`

• `'integerconstraints'`

• `rngstate` — State of the MATLAB random number generator, just before the algorithm started. You can use the values in `rngstate` to reproduce the output of `ga`. See Reproduce Results.

• `generations` — Number of generations computed.

• `funccount` — Number of evaluations of the fitness function.

• `message` — Reason the algorithm terminated.

• `maxconstraint` — Maximum constraint violation, if any.

• `hybridflag` — Exit flag from the hybrid function. Relates to the `HybridFcn` `options`. Not applicable to `gamultiobj`.

Final population, returned as a `PopulationSize`-by-`nvars` matrix. The rows of `population` are the individuals.

Final scores, returned as a column vector.

• For non-integer problems, the final scores are the fitness function values of the rows of `population`.

• For integer problems, the final scores are the penalty fitness values of the population members. See Integer ga Algorithm.

collapse all

### Complementarity Measure

In the Augmented Lagrangian nonlinear constraint solver, the complementarity measure is the norm of the vector whose elements are ciλi, where ci is the nonlinear inequality constraint violation, and λi is the corresponding Lagrange multiplier. See Augmented Lagrangian Genetic Algorithm.

## Tips

• To write a function with additional parameters to the independent variables that can be called by `ga`, see Passing Extra Parameters.

• For problems that use the population type `Double Vector` (the default), `ga` does not accept functions whose inputs are of type `complex`. To solve problems involving complex data, write your functions so that they accept real vectors, by separating the real and imaginary parts.

## Algorithms

For a description of the genetic algorithm, see How the Genetic Algorithm Works.

For a description of the mixed integer programming algorithm, see Integer ga Algorithm.

For a description of the nonlinear constraint algorithms, see Nonlinear Constraint Solver Algorithms.

## Alternative Functionality

### App

The Optimize Live Editor task provides a visual interface for `ga`.

## Compatibility Considerations

expand all

Behavior changed in R2019b

## References

[1] Goldberg, David E., Genetic Algorithms in Search, Optimization & Machine Learning, Addison-Wesley, 1989.

[2] A. R. Conn, N. I. M. Gould, and Ph. L. Toint. “A Globally Convergent Augmented Lagrangian Algorithm for Optimization with General Constraints and Simple Bounds”, SIAM Journal on Numerical Analysis, Volume 28, Number 2, pages 545–572, 1991.

[3] A. R. Conn, N. I. M. Gould, and Ph. L. Toint. “A Globally Convergent Augmented Lagrangian Barrier Algorithm for Optimization with General Inequality Constraints and Simple Bounds”, Mathematics of Computation, Volume 66, Number 217, pages 261–288, 1997.

## Extended Capabilities

### Topics

Introduced before R2006a

Watch now