目标函数:
代码:
function o=func21(x)
o=sum(x.^2-10*cos(2*pi.*x)+10);
end
%%实值遗传算法求函数极值%%%%
%%%%%初始化参数%%%%%
clear all; %清除所有变量
close all; %清图
clc; %清屏
clear all;
NP=1000; %染色体数目
Dim=30; %基因数目
Pc=0.95; %交叉率,一般取0.25~1
Pm=0.01; %变异率,一般取0.001~0.1
G=1000; %最大遗传代数,一般100~1000
Xs=5.21; %定义域上限
Xx=-5.21; %定义域下限
f=rand(Dim,NP)*(Xs-Xx)+Xx; %随机获得初始种群
trace=zeros(1,G); %预先分配内存
Fit=zeros(1,NP); %预先分配内存
%%%%%遗传算法循环%%%%%
for gen=1:G
%%%%%按适应度升序排列%%%%%
for np=1:NP
Fit(np)=func21(f(:,np));
end
[SortFit,Index]=sort(Fit);
Sortf=f(:,Index);
%%%%%采用君主方案进行选择交叉操作%%%%%
Emper=Sortf(:,1);
NoPoint=round(Dim*Pc);
PoPoint=randi([1 Dim],NoPoint,NP/2);
nf=Sortf;
for i=1:NP/2
nf(:,2*i-1)=Emper;
nf(:,2*i)=Sortf(:,2*i);
for k=1:NoPoint
nf(PoPoint(k,i),2*i-1)=nf(PoPoint(k,i),2*i);
nf(PoPoint(k,i),2*i)=Emper(PoPoint(k,i));
end
end
%%%%%变异操作%%%%%
for m=1:NP
for n=1:Dim
r=rand(1,1);
if r<Pm
nf(n,m)=rand(1,1)*(Xs-Xx)+Xx;
end
end
end
f=nf;
trace(gen)=SortFit(1);
end
Bestf=Sortf(:,1)
func21(Bestf)
trace(end);
figure
plot(trace)
xlabel('迭代次数')
ylabel('目标函数值')
title('适应度进化曲线')
结果展示