📄 genetic.m
字号:
function [X,Y,x,y,fx,vx,vmfit,P] = genetic(numfunction,v,ger,pc,pm)
[N,L] = size(v); ger = 200; pc = 0.5; pm = 0.01; updatef=0;c=0;
if nargin == 1
[N,L] = size(v); ger = 200; pc = 0.5; pm = 0.01;c=0;
end
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));
switch numfunction
case 1
f = '-1 * x .* sin(2 * pi .* x) + y.* sin(2 * pi .* y) + 1';
case 2
f = '1 * x .* sin(4 * pi .* x) - 1 * y.* sin(4 * pi .* y + pi) + 1';
case 3
f = '1+1 * x .* sin(4 * pi .* x) - 1 * y.* sin(4 * pi .* y + pi) + sin(6*sqrt(x.*x+y.*y))./(6*sqrt(x.*x+y.*y+0.000000000000001))';
case 4
f='-(x.^2+2*y.^2)+0.3*cos(3*3.1415926*x)-0.3*cos(4*3.1415926*y)-0.3';
case 5
f='10+sin(1./x)./((x-0.6).*(x-0.6)+0.1)';
case 6
f='-(cos(2.*x+1)+2.*cos(3.*x+2)+3.*cos(4.*x+3)+4.*cos(5.*x+4)+5.*cos(6.*x+5)).*(cos(2.*y+1)+2.*cos(3.*y+2)+3.*cos(4.*y+3)+4.*cos(5.*y+4)+5.*cos(6.*y+5))';
c=1;
end
[x,y] = meshgrid(-1:0.05:1,-1:0.05:1); vxp = x; vyp = y;
vzp = eval(f); PRINT = 1;
% 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);
plotnow(PRINT,vxp,vyp,vzp,x,y,fit,1,1); title('Initial Population');
disp('Press any key to continue...'); pause;
% Generations
t0 = clock;
while it <= ger %& sol1 <= 2.26,
% Selection
for i=1:N
sp(i)=(fit(i)+1)/sum(fit(i)+1);
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
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;
for j=point:(L-1)
ch=v(cindex(i),j);
v(cindex(i),j)=v(cindex(i+1),j);
v(cindex(i+1),j)=ch;
end
end
end
% Mutation
M=rand(N,L)<=pm;
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);
plotnow(PRINT,vxp,vyp,vzp,x,y,fit,it,5);
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.5f',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));
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -