📄 ycsf.m
字号:
%Generic Algorithm for function f(x1,x2) optimum,本程序求
%F(s)=100*(x1^2-x2)^2+(1-x1)^2在[-2.048,2.048]之间的最大值
clear all;
close all;
%Parameters,初始化
Size=80; %种群大小
G=100; %迭代次数
CodeL=10;%编码长达
%变量的上下限
umax=2.048;
umin=-2.048;
%编码,(可以采用其他编码方法,且可改进该种编码代码)
E=round(rand(Size,2*CodeL)); %Initial Code,初始种群
%Main Program,主程序
for k=1:1:G%对于每次迭代
time(k)=k; %记录,便于画出迭代图
for s=1:1:Size %对于每个种群
m=E(s,:);
y1=0;y2=0;
%Uncoding,解码过程
m1=m(1:1:CodeL);
for i=1:1:CodeL
y1=y1+m1(i)*2^(i-1);
end
x1=(umax-umin)*y1/1023+umin;%2^10-1=1023
m2=m(CodeL+1:1:2*CodeL);
for i=1:1:CodeL
y2=y2+m2(i)*2^(i-1);
end
x2=(umax-umin)*y2/1023+umin;
F(s)=100*(x1^2-x2)^2+(1-x1)^2;%求目标函数值
end
Ji=1./F;%求出
%****** Step 1 : Evaluate BestJ ******,找出当前最好的适应值BestJ(k)
BestJ(k)=min(Ji);
fi=F; %Fitness Function,目标函数值
[Oderfi,Indexfi]=sort(fi); %Arranging fi small to bigger,对适应度排序
Bestfi=Oderfi(Size); %Let Bestfi=max(fi),最优值
BestS=E(Indexfi(Size),:); %Let BestS=E(m), m is the Indexfi belong to max(fi)
bfi(k)=Bestfi; %记下当前最优值
%****** Step 2 : Select and Reproduct Operation******,选择和复制操作
%轮盘赌法
fi_sum=sum(fi);
fi_Size=(Oderfi/fi_sum)*Size; %Oderfi为排序后的适应值
fi_S=floor(fi_Size); %Selecting Bigger fi value,轮盘赌法选择该种群
%floor()求出比fi_Size小的第一个整数
kk=1;
for i=1:1:Size %对于每个种群fi_Size
for j=1:1:fi_S(i) %Select and Reproduce
TempE(kk,:)=E(Indexfi(i),:);
kk=kk+1; %kk is used to reproduce
end
end
%************ Step 3 : Crossover Operation ************,交叉
pc=0.60; %交叉概率
n=ceil(20*rand); %产生
%ceil(A)求出矩阵A中每个元素大于等于其的最小整数
for i=1:2:(Size-1) %
temp=rand; %
if pc>temp %Crossover Condition,交叉条件
for j=n:1:20 %E为种群矩阵
TempE(i,j)=E(i+1,j);
TempE(i+1,j)=E(i,j);
end
end
end
TempE(Size,:)=BestS;
E=TempE; %交叉后的新种群
%************ Step 4: Mutation Operation **************
%pm=0.001;
%pm=0.001-[1:1:Size]*(0.001)/Size; %Bigger fi, smaller Pm
%pm=0.0; %No mutation
pm=0.1; %Big mutation,变异概率
for i=1:1:Size %对于每个种群
for j=1:1:2*CodeL %对于每个编码位
temp=rand;
if pm>temp %Mutation Condition,变异条件
if TempE(i,j)==0
TempE(i,j)=1;
else
TempE(i,j)=0;
end
end
end
end
%Guarantee TempPop(30,:) is the code belong to the best individual(max(fi))
%保证TempPop(30,:)是属于最优个体
TempE(Size,:)=BestS;
E=TempE; %更新种群
end
%迭代结束
Max_Value=Bestfi %求解出的最优值
BestS %求解出的变量取值
x1
x2
figure(1); %画图,这个图很丑
plot(time,BestJ);
xlabel('Times');ylabel('Best J');
figure(2);
plot(time,bfi);
xlabel('times');ylabel('Best F');
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -