Optimize Using ga

Calling the Function ga at the Command Line

To use the genetic algorithm at the command line, call the genetic algorithm function ga with the syntax

[x fval] = ga(@fitnessfun, nvars, options)


  • @fitnessfun is a handle to the fitness function.

  • nvars is the number of independent variables for the fitness function.

  • options contains options for the genetic algorithm. If you do not pass in this argument, ga uses its default options.

The results are given by

  • x — Point at which the final value is attained

  • fval — Final value of the fitness function

For an example, see Finding the Minimum from the Command Line.

Using the function ga is convenient if you want to

  • Return results directly to the MATLAB® workspace

  • Run the genetic algorithm multiple times with different options, by calling ga from a file

Use the Optimization App

To open the Optimization app, enter

at the command line, or enter optimtool and then choose ga from the Solver menu.

You can also start the tool from the MATLAB Apps tab.

To use the Optimization app, you must first enter the following information:

  • Fitness function — The objective function you want to minimize. Enter the fitness function in the form @fitnessfun, where fitnessfun.m is a file that computes the fitness function. Compute Objective Functions explains how write this file. The @ sign creates a function handle to fitnessfun.

  • Number of variables — The length of the input vector to the fitness function. For the function my_fun described in Compute Objective Functions, you would enter 2.

You can enter constraints or a nonlinear constraint function for the problem in the Constraints pane. If the problem is unconstrained, leave these fields blank.

To run the genetic algorithm, click the Start button. The tool displays the results of the optimization in the Run solver and view results pane.

You can change the options for the genetic algorithm in the Options pane. To view the options in one of the categories listed in the pane, click the + sign next to it.

For more information,

Was this topic helpful?