genetic algorithm code with more than three variables
조회 수: 9 (최근 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!