|
楼主 |
发表于 2007-10-28 12:25
|
显示全部楼层
维数的问题貌似已经解决,但是程序还是有问题,大家帮忙看一下,哈
目标函数: (用了内点惩罚函数法)
function z=myfun5(x1,x2)
z=21.5+x1.*sin(4*pi*x1)+x2.*sin(20*pi*x2);
g=[-x1-3.0 x1-12.1 -x2+4.1 x2-5.8];B=sum(1./g);
global k;
z=-(z+0.5^k*B);
遗传算法:
%Simple Genetic Algorithm
clear;clc;tic;
%initialise
popsize=10;stringlength=33;stringlength2=18;pc=0.9;pm=0.01;
a=-3.0;b=12.1;c=4.1;d=5.8;
pop=round(rand(popsize,stringlength+3));
pop(:,stringlength+1)=2.^(size(pop(:,1:stringlength2),2)-1:-1:0)*pop(:,1:stringlength2)'*(b-a)/(2.^stringlength2-1)+a;
pop(:,stringlength+2)=2.^(size(pop(:,stringlength2+1:stringlength),2)-1:-1:0)*pop(:,stringlength2+1:stringlength)'*(d-c)/(2.^(stringlength-stringlength2)-1)+c;
pop(:,stringlength+3)=myfun5(pop(:,stringlength+1:stringlength+2));
for T=1:100
%roulette selection
totalfit=sum(pop(:,stringlength+3));
prob=pop(:,stringlength+3)./totalfit;
prob=cumsum(prob);
rns=sort(rand(popsize,1));
fitin=1;newin=1;
while newin<=popsize
if rns(newin)<prob(fitin)
pop(newin,:)=pop(fitin,:);
newin=newin+1;
else
fitin=fitin+1;
end
end
%crossover
for i=1:2:popsize-1
if rand<pc
cpoint=round(rand*(stringlength-2))+1;
pop(i,:)=[pop(i,1:cpoint) pop(i+1,cpoint+1:stringlength)];
pop(i+1,:)=[pop(i+1,1:cpoint) pop(i,cpoint+1:stringlength)];
end
end
%mutation
for i=1:popsize
if rand<pm
mpoint=round(rand*(stringlength-1))+1;
pop(i,mpoint)=1-pop(i,mpoint);
end
end
%new pop
pop(:,stringlength+1)=2.^(size(pop(:,1:stringlength2),2)-1:-1:0)*pop(:,1:stringlength2)'*(b-a)/(2.^stringlength2-1)+a;
pop(:,stringlength+2)=2.^(size(pop(:,stringlength2+1:stringlength),2)-1:-1:0)*pop(:,stringlength2+1:stringlength)'*(d-c)/(2.^(stringlength-stringlength2)-1)+c;
pop(:,stringlength+3)=myfun5(pop(:,stringlength+1:stringlength+2));
end
%result
[mm,h]=max(pop(:,stringlength+3));
x1=2.^(size(pop(h,1:stringlength2),2)-1:-1:0)*pop(h,1:stringlength2)'*(b-a)/(2.^stringlength2-1)+a;
x2=2.^(size(pop(:,stringlength2+1:stringlength),2)-1:-1:0)*pop(:,stringlength2+1:stringlength)'*(d-c)/(2.^(stringlength-stringlength2)-1)+c;
toc;
x=[x1,x2]
??? Input argument "x2" is undefined.
Error in ==> myfun5 at 2
z=21.5+x1.*sin(4*pi*x1)+x2.*sin(20*pi*x2);
Error in ==> GA at 9
pop(:,stringlength+3)=myfun5(pop(:,stringlength+1:stringlength+2));
唉,为什么自己觉得对的总是出错呢:@L
[ 本帖最后由 sun1993 于 2007-10-28 12:28 编辑 ] |
|