%这是一个用MATLAB编的免疫克隆算法优化函数的程序,免疫克隆算法是一种比较新的有效的优化算法,近两年对他的研究很多。
function [] = CA
clear
clc
tic;
gen=500;N=65;L=22;n1=10;pm=0.1;fat=0.2;
P=init(N,L);
xmin=0;xmax=9;
f='sin(x)+10*sin(x.*5)+7*cos(x.*4)';
vfx=[];vmfit=[];
it=0;
while it<gen
it=it+1;
x=decode(P(:,1:22),xmin,xmax);
fit=eval(f);
if it==1
figure(1);fplot(f,[xmin,xmax]);grid on;hold on;
plot(x,fit,'k*');title('(a)抗体的初始位置分布图');xlabel('x');ylabel('y');
end
if it==gen
figure(2);fplot(f,[xmin,xmax]);grid on;hold on;
plot(x,fit,'k*');title('(b)抗体的最终位置分布图');xlabel('x');ylabel('y');
end
T=[];
[a,ind]=sort(fit);
valx=x(ind(end-n1+1:end));
fx=a(end-n1+1:end);
vfx=[vfx fx(end)];
[T,pcs]=reprod(n1,fat,N,ind,P,T);
T=Hypermutation(T,L,pm,xmax,xmin);
T(pcs,:)=P(fliplr(ind(end-n1+1:end)),:);
x=decode(T(:,1:22),xmin,xmax);
fit=eval(f);pcs=[0 pcs];vmfit=[vmfit mean(fit)];
for i=1:n1
[out(i),bcs(i)]=max(fit(pcs(i)+1:pcs(i+1)));
bcs(i)=bcs(i)+pcs(i);
end
P(fliplr(ind(end-n1+1:end)),:)=T(bcs,:);
end
[aa,bb]=max(fit)
x(bb)
toc
function ab=init(n1,s)
ab=2.*rand(n1,s)-1;
save ab;
ab=hardlim(ab);
function x=decode(v,xmin,xmax) % 反译码
v=fliplr(v);
s=size(v);
aux=0:1:21;aux=ones(s(1),1)*aux;
x1=sum((v.*2.^aux)');
x=xmin+(xmax-xmin)*x1./4194303;
function T=Hypermutation(T,L,pm,xmax,xmin); %变异
M=rand(size(T,1),L)<=pm;
M=T-2.*(T.*M)+M;
k=round(log(10*(xmax-xmin)));
k=1;
T(:,k:L)=M(:,k:L);
function [T,pcs]=reprod(n1,fat,N,ind,P,T) %复制
if n1==1
cs=N;
T=ones(N,1)*P(ind(1),:);
else
for i=1:n1
%cs(i)=ceil(fat*N/i);
cs(i)=round(fat*N);
save cs;
pcs(i)=sum(cs);
T=[T;ones(cs(i),1)*P(ind(end-i+1),:)];
end
end
评论0