% GA_zuiyou
clc;clear
x=-1:0.01:2;
y=2+x.*sin(10*pi*x);
plot(x,y,'LineWidth',1.5);
hold on
%初始化參數
T=100;%仿真代數
N=10;% 羣體規模
pc=0.8;pm=0.05;%交叉變異概率
umax=2;umin=-1;%參數取值範圍
L=12;%單個參數字串長度,總編碼長度 L
bval=round(rand(N,L)); %生成初始種羣
bestv=-inf;%最優適應度初值 %迭代開始
for ii=1:T
%解碼,計算適應度
for i=1:N
y1=0;
for j=1:1:L
y1=y1+bval(i,L-j+1)*2^(j-1);
end
x=(umax-umin)*y1/(2^L-1)+umin; %二進制變十進制
obj(i)=2+x.*sin(10*pi*x);
xx(i,:)=x;
plot(x,obj(i),'k*');
hold on
end
func=obj;%目標函數轉換爲適應度函數
p=func./sum(func);
q=cumsum(p);
[fmax,indmax]=max(func);%求當代最佳個體
if fmax>=bestv
bestv=fmax;%到目前爲止最優適應度值
bvalxx=bval(indmax,:);%到目前爲止最佳位串
optxx=xx(indmax);
end
Best(ii)=fmax;
Bfit1(ii)=bestv; % 存儲代的最優適應度
%%%%遺傳操作開始 %輪盤賭選擇
for i=1:N
r=rand;
tmp=find(r<=q);
newbval(i,:)=bval(tmp(1),:);
end
newbval(N,:)=bvalxx;%最優保留
bval=newbval;
%單點交叉
for i=1:2:(N-1)
cc=rand;
if cc<pc
point=ceil(rand*(L-1)); %交叉點數
ch=bval(i,:);
bval(i,point+1:L)=bval(i+1,point+1:L);
bval(i+1,point+1:L)=ch(1,point+1:L);
end
end
% bval(N,:)=bvalxx;%最優保留
%位點變異
for i=1:N
for j=1:(L)
pb=rand;
if(pb<pm)
bval(i,j)=1-bval(i,j);
end
end
end
end %輸出
figure(2) ;
plot(Best,'LineWidth',1.5);% 最優適應度進化曲線
hold on
plot(Bfit1,'k','LineWidth',1.5);% 最優適應度進化曲線
hold on
plot(max(y)*ones(1,100),'-.r','LineWidth',1.5);
%bestv; %輸出最優適應度值
%optxx; %輸出最優參數
axis([1,100,0,4])
max(y)
bestv;
optxx;