how to plot optimization figure of genetic algorithm with y as number of iteration and x as fitness value in matlab

To plot the optimization figure of a genetic algorithm with the y-axis as the number of iterations and the x-axis as the fitness value in MATLAB, you can use the following steps:

  1. Create a genetic algorithm optimization problem using the ga function in MATLAB. Set the PlotFcn option to a custom plot function or use the built-in plot function gaplotbestf to track the best fitness value over generations.

  2. Run the genetic algorithm using the optimization problem. This will generate a set of variables, including the fitness values and the number of iterations.

  3. Extract the fitness values and the number of iterations from the genetic algorithm result.

  4. Plot the fitness values on the y-axis and the number of iterations on the x-axis using the plot function in MATLAB.

Here's an example code that demonstrates these steps:

main.m
% Define the fitness function (replace with your own fitness function)
fitnessFunc = @(x) (x(1) - 3)^2 + (x(2) + 1)^2;

% Define the number of variables and the fitness function
nVars = 2;
fitnessFcn = fitnessFunc;
 
% Create the OptimizationOptions object
options = optimoptions('ga', 'PlotFcn', @gaplotbestf);

% Run the genetic algorithm
[x, fval, exitFlag, output] = ga(fitnessFcn, nVars, [], [], [], [], [], [], [], options);

% Extract the best fitness values and iteration numbers
fitnessValues = output.bestfvals;
iterationNumbers = output.iterations;

% Plot the optimization figure
plot(iterationNumbers, fitnessValues);
xlabel('Number of Iterations');
ylabel('Fitness Value');
title('Genetic Algorithm Optimization');
729 chars
23 lines

This code defines a simple fitness function and sets up a genetic algorithm optimization problem. The options object is created with the PlotFcn option set to @gaplotbestf which will automatically plot the best fitness value over generations. After running the genetic algorithm, the best fitness values and the iteration numbers are extracted and then plotted using the plot function.

Note that the fitness function used in this example is a simple 2-variable function. You will need to replace it with your own fitness function depending on your optimization problem.

gistlibby LogSnag