genetic algorithm code with more than three variables

10 次查看(过去 30 天)
I need genetic algorithm code with more than three variables

采纳的回答

Sam Chak
Sam Chak 2022-6-16
Maybe this example would give you the basics of using the genetic algorithm (GA) to minimize a multivariate function. The problem to find the roots of a Cubic function given by
.
Since the cubic function has no global minima, and the GA only minimizes a given function, then the root-finding problem must be reformulated to become a convex optimization problem.
x = linspace(1, 6, 501);
y1 = x.^3 - 10*x.^2 + 31*x - 30; % cubic function
y2 = abs(x.^3 - 10*x.^2 + 31*x - 30); % absolute value of cubic function
subplot(2, 1, 1) % 1st subplot
plot(x, y1, 'linewidth', 1.5)
title('Roots of a Cubic function')
subplot(2, 1, 2) % 2nd subplot
plot(x, y2, 'linewidth', 1.5)
title('Absolute value of the Cubic function')
To setup the fitness function for GA, you can do as follows:
f = @(x) abs(x(1).^3 - 10*x(1).^2 + 31*x(1) - 30) + abs(x(2).^3 - 10*x(2).^2 + 31*x(2) - 30) + abs(x(3).^3 - 10*x(3).^2 + 31*x(3) - 30);
nvars = 3; % 3 variables
A = -eye(nvars); % Constraints A*x <= b to search for solutions on the positive side
b = zeros(nvars, 1);
Aeq = [];
beq = [];
lb = [1.0 2.5 4.0]; % bounds setup xlb < x < ub for x(1), x(2), x(3)
ub = [2.5 4.0 6.0];
rootx = ga(f, nvars, A, b, Aeq, beq, lb, ub)
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
rootx = 1×3
2.0000 3.0000 5.0000
  9 个评论
Sam Chak
Sam Chak 2022-6-21
编辑:Sam Chak 2022-6-21
To make it easy for you to visualize a multivariate function in n-dimension, I have simplified the function to only two variables, a bivariate function given by
.
If you haven't noticed yet, is linear functional as shown by the flat surface in the 3D plot below:
[X, Y] = meshgrid(0:12/60:6);
Z = X + 2*Y - 5;
surf(X, Y, Z)
Since the variables are constrained to non-negative values (in this example, from 0 to 6), naturally the minimum of the function must be at , as clearly shown in the plot.
Thus, the Genetic Algorithm will return the solution as close as possible to .
f = @(x) x(1) + 2*x(2) - 5;
nvars = 2; % 2 variables, x1, x2
A = -eye(nvars); % Constraints A*x <= b to force GA to search for solutions on the positive side
b = zeros(nvars, 1);
Aeq = [];
beq = [];
lb = [0 0]; % bounds setup lb < x < ub for x1, x2
ub = [6 6];
xsol = ga(f, nvars, A, b, Aeq, beq, lb, ub)
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
xsol = 1×2
0 0
You are advised to revisit your optimization problem and reformulate the objective function (if relevant, as a Convex function), perhaps together with meaningful constraints as well.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Genetic Algorithm 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by