genetic algorithm code with more than three variables
10 ビュー (過去 30 日間)
古いコメントを表示
I need genetic algorithm code with more than three variables
0 件のコメント
採用された回答
Sam Chak
2022 年 6 月 16 日
Hi @huda nawaf
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)
9 件のコメント
Sam Chak
2022 年 6 月 21 日
編集済み: Sam Chak
2022 年 6 月 21 日
Hi @huda nawaf
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
.
[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)
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 Center および File Exchange で Genetic Algorithm についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!