## CSDN博客

### Matlab 7 GA

1、首先编写fitness函数，函数内容见后面的引用。

function score = my_func1(pop)
%f(x1,x2)=21.5+x1*sin(4*pi*x1)+x2*sin(20*pi*x2)
%-3.0<=x1<=12.1; 4.1<=x2<=5.8
score = -21.5 - pop(1)*sin(4*pi*pop(1)) - pop(2)*sin(20*pi*pop(2));

% X = GA(FITNESSFCN,NVARS) finds the minimum of FITNESSFCN using
% GA. NVARS is the dimension (number of design variables) of the
% FITNESSFCN. FITNESSFCN accepts a vector X of size 1-by-NAVRS,
% and returns a scalar evaluated at X.
%
% X = GA(FITNESSFCN,NAVRS,OPTIONS) finds the minimum for
% FITNESSFCN with the default optimization parameters replaced by values
% in the structure OPTIONS. OPTIONS can be created with the GAOPTIMSET
% function.
ga 是寻找最小值的，所以将原函数取负。

[parse]lihuanc[/parse]

f(x1,x2)=21.5+x1*sin(4*pi*x1)+x2*sin(20*pi*x2)
-3.0<=x1<=12.1 4.1<=x2<=5.8

[parse]zonly[/parse]

x1*=11.6255 x2*＝5.7250

[parse]easyworm[/parse]

lingo 8.0的计算结果为37.45030

2、gatool 的用法

f(x1*,x2*)=-my_func1(x1*,x2*)=38.84741978236206,
where x1*=11.62378; x2*=5.72501

3、ga 函数的使用

opt1 = gaoptimset;
opt1.PopInitRange = [[-3.0 4.1];[12.1 5.8]];
opt1.PopulationSize = 1000;
opt1.MutationFcn=@mutationuniform;
[x, fval] = ga(@my_func1,2,opt1)

>> opt1

opt1 =

PopulationType: 'doubleVector'
PopInitRange: [2x2 double]
PopulationSize: 1000
EliteCount: 2
CrossoverFraction: 0.80000000000000
MigrationDirection: 'forward'
MigrationInterval: 20
MigrationFraction: 0.20000000000000
Generations: 100
TimeLimit: Inf
FitnessLimit: -Inf
StallGenLimit: 50
StallTimeLimit: 20
InitialPopulation: []
InitialScores: []
PlotInterval: 1
CreationFcn: @gacreationuniform
FitnessScalingFcn: @fitscalingrank
SelectionFcn: @selectionstochunif
CrossoverFcn: @crossoverscattered
MutationFcn: @mutationuniform
HybridFcn: []
Display: 'final'
PlotFcns: []
OutputFcns: []
Vectorized: 'off'

>> [x, fval] = ga(@my_func1,2,opt1)
Optimization terminated: stall generations limit exceeded.

x =

11.60992040806107 5.72602745388080

fval =

-38.61619496300001

>>

（缩略图，点击图片链接看原图）

function y = my_func2(x)
%fmax
r=sqrt((x(1)-50)^2+(x(2)-50)^2)+exp(1);
y=-(sin(r)/r+1);

function y = my_func2a(x)
%fmin
r=sqrt((x(1)-50)^2+(x(2)-50)^2)+exp(1);
y=(sin(r)/r+1);

http://bbs.matwav.com/post/view?bid=7&id=45307&sty=0&tpg=2&ppg=1&age=0#45307

minimize f(x) = 0.7827663723309104;
maximize f(x) = 1.1283745483594003

（缩略图，点击图片链接看原图）

0 0