易错点:
1.要新建一个文件夹
2.打开该文件夹,在新建脚本或函数。
代码如下:
GA.m
%基于遗传算法的函数优化 GA.m
clc;
clear;close all;
p = rand(50,22);
v = 2*rand(50,22)-1;
v=hardlim(v);
[N,L] = size(v); ger = 200; pc = 0.5; pm = 0.01; updatef=0;c=0;
disp(sprintf('Number of generations: %d',ger));
disp(sprintf('Population size: %d',N));
disp(sprintf('Crossover probability: %.3f',pc));
disp(sprintf('Mutation probability: %.3f',pm));
f='-1*(x.^2+y.^2)';
% General parameters & Initial operations
sol1=1; vmfit = []; it = 1; vx = []; C = [];updatef=-10;
x = decod(v(:,1:11),11); y = decod(v(:,12:end),11); fit = eval(f);
% Generations
t0 = clock;
while it <= ger
% Selection 轮盘赌
for i=1:N
sp(i)=(fit(i)+3)/sum(fit+3);%
end
for i=2:N
sp(i)=sp(i-1)+sp(i);
end
for i=1:N
p=rand(1); sindex=1;
while p > sp(sindex)
sindex=sindex+1; %寻找要选择个体的位置
end
newv(i,:)=v(sindex,:);
end
for i=1:N
v(i,:)=newv(i,:);%用选择出的个体构成的种群替代旧的种群
end
% Crossver
for i=1:N
cindex(i)=i;
end
for i=1:N %产生要配对的父代的序号;经过N次顺序调换,将原有顺序打乱,使相邻两个个体作为交叉的父代
point=unidrnd(N-i+1);
temp=cindex(i);
cindex(i)=cindex(i+point-1);
cindex(i+point-1)=temp;
end
for i=1:2:N
p=rand(1);
if(p<pc)
point=unidrnd(L-1)+1;%1<point<L 产生交叉点
for j=point:(L-1) %交叉
ch=v(cindex(i),j);
v(cindex(i),j)=v(cindex(i+1),j); %cindex中相邻的两个为两个父代的序号
v(cindex(i+1),j)=ch;
end
end
end
% Mutation
M=rand(N,L)<=pm;%产生(N,L)维的01矩阵,为1的位置进行变异
v=v-2.*(v.*M)+M;
% Evaluatefitness & Evolution
x = decod(v(:,1:11),11); y = decod(v(:,12:end),11); fit = eval(f);
[sol1,indb1] = max(fit);
if updatef>=sol1
sol1=updatef;
v(indb1,:)=updatec;
end
updatef=sol1;
updatec=v(indb1,:);
[sol2,indb2] = min(fit);
v(indb2,:) = v(indb1,:);
x = decod(v(:,1:11),11); y = decod(v(:,12:end),11); fit = eval(f);
media = mean(fit);
vx = [vx sol1]; vmfit = [vmfit media];
if rem(it,1) == 0 | it == 10,
if c~=1
disp(sprintf('Gen.: %d x: %2.5f y: %2.5f Av: %2.2f f(x,y): %2.40f',it,x(indb1),y(indb1),media,sol1));
else
disp(sprintf('Gen.: %d Av: %2.2f f(x,y): %2.5f',it,media,sol1));
end
end;
it = it + 1;
end;
T = etime(clock,t0); %F = flops - f0;
X=x;Y=y;
x = x(indb1); y = y(indb1); fx = sol1; P = v;
disp(sprintf('the total time is %2.4f',T));
disp(sprintf('Maximum found [f(x,y)]: [%.2f]',fx));
% xx=vx;yy=vmfit;
figure(2); plot(vx,'k');
title('f(x,y) x Mean'); xlabel('Generations'); ylabel('f(x,y)');
hold on; plot(vmfit,'k:'); legend('best','mean',0);hold off;
decod.m
function x = decod(v,l)%解码子函数
%********************************
[length ,width]=size(v);
x=zeros(1,length);
for i=1:length
sum=0;
for j=1:l
sum=sum+v(i,j)*2^(1-j);
end
x(i)=-1+sum+2/(2^l-1);
end