genetic algorithm code with more than three variables
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
I need genetic algorithm code with more than three variables
채택된 답변
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)
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
rootx = 1×3
2.0000 3.0000 5.0000
댓글 수: 9
thanks, but need to know if my problem has more than three variables, can use this code?
Hi @huda nawaf
Can, just modify the above multivariate function in your problem and set the number of variables in nvars.
See example below:
fun = @(x) (x(1) - 2).^2 + (x(2) - 3).^2 + (x(3) - 5).^2 + (x(4) - 7).^2 + (x(5) - 11).^2 + (x(6) - 13).^2;
nvars = 6; % 6 variables
A = -eye(nvars); % Constraints A*x <= b to search for solutions on the positive side
b = zeros(nvars, 1);
x = ga(fun, nvars, A, b)
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
x = 1×6
2.0001 3.0001 5.0000 7.0006 11.0002 12.9998
If you find this tutorial on using ga() in the MATLAB code helpful, consider accepting ✔ and voting 👍 the Answer. Thanks, @huda nawaf.
my function
f(x) = ((a + 2b + 3c + 4d) - 30).
all var are integers between 0 and 30
when I applied the above code such as
nvars=6;
x=ga(fun,nvars)
this message appears
Fitness function must be a function handle.
thanks in advance
Good. You'll be fine.
- Follow the format of how the fitness function is entered and
- identify the number of variables correctly.
- Also enter your bounds as shown in the example.
Post these 3 things later so that I can check.
thanks for help
fun=@(x)((x(1) + 2*x(2) + 3*x(3) + 4*x(4)) - 30);
>> nvars=4;
>> A = -eye(nvars);
>> b== zeros(nvars, 1);
>> x=ga(fun,nvars,A,b,0,30)
Error using preProcessLinearConstr (line 64)
The number of columns in Aeq must be the same as the
length of X0.
Error in gacommon (line 104)
[Iterate.x,Aineq,bineq,Aeq,beq,lb,ub,msg,exitFlag] = ...
Error in ga (line 319)
[x,fval,exitFlag,output,population,scores,FitnessFcn,nvars,Aineq,bineq,Aeq,beq,lb,ub,
when apply thefunction below without make the constrains, i got:
x=ga(fun,nvars)
Optimization terminated: maximum number of generations exceeded.
x =
0.5246 -16.1315 -21.8449 -18.3718
In fact I do not know what A and b means, but i can guss lb and ub are the constrains (in my case 0-30)
If the MATLAB code solves your given problem, consider accepting ✔ and voting 👍 the Answer. Thanks!
f = @(x) (x(1) + 2*x(2) + 3*x(3) + 4*x(4)) - 30;
nvars = 4; % 4 variables, x1, x2, x3, x4
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 0 0]; % bounds setup lb < x < ub for x1, x2, x3, x4
ub = [30 30 30 30];
xsol = ga(f, nvars, A, b, Aeq, beq, lb, ub)
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
xsol = 1×4
1.0e-04 *
0.6638 0.6049 0.2772 0.1609
hi sam , thanks
the code now is running without problems and i made vote and accept the answer
but still I have query, I think f must equal zero, is not?
my example from a website, I wana to apply the code then apply my real problem.
in website the obj. fun is a + 2b + 3c + 4d=30
then he converted into f=a + 2b + 3c + 4d-30
but i think it is must be zero, why f = -29.99
in same time how know the code is minimize or maximize?
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)
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.
huda nawaf
2022년 6월 21일
이동: madhan ravi
2023년 11월 18일
thank u very much
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Genetic Algorithm에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
