Products & Services Solutions Academia Support User Community Company

Learn more about Genetic Algorithm and Direct Search Toolbox   

Writing Files for Functions You Want to Optimize

Computing Objective Functions

To use Genetic Algorithm and Direct Search Toolbox functions, you must first write an M-file (or else an anonymous function) that computes the function you want to optimize. The M-file should accept a vector, whose length is the number of independent variables for the objective function, and return a scalar. This section shows how to write the M-file.

Example — Writing an M-File

The following example shows how to write an M-file for the function you want to optimize. Suppose that you want to minimize the function

The M-file that computes this function must accept a vector x of length 2, corresponding to the variables x1 and x2, and return a scalar equal to the value of the function at x. To write the M-file, do the following steps:

  1. Select New from the MATLAB File menu.

  2. Select M-File. This opens a new M-file in the editor.

  3. In the M-file, enter the following two lines of code:

    function z = my_fun(x)
    z = x(1)^2 - 2*x(1)*x(2) + 6*x(1) + x(2)^2 - 6*x(2);
    
  4. Save the M-file in a folder on the MATLAB path.

To check that the M-file returns the correct value, enter

my_fun([2 3])

ans =

    -5

Maximizing vs. Minimizing

Genetic Algorithm and Direct Search Toolbox optimization functions minimize the objective or fitness function. That is, they solve problems of the form

If you want to maximize f(x), you can do so by minimizing –f(x), because the point at which the minimum of –f(x) occurs is the same as the point at which the maximum of f(x) occurs.

For example, suppose you want to maximize the function

described in the preceding section. In this case, you should write your M-file to compute

and minimize g(x).

Constraints

Many Genetic Algorithm and Direct Search Toolbox functions accept bounds, linear constraints, or nonlinear constraints. To see how to include these constraints in your problem, see Writing Constraints in the Optimization Toolbox User's Guide. Direct links to sections:

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS