資源簡(jiǎn)介
蟻群算法求函數(shù)最大值的程序
function [F]=F(x1,x2) %目標(biāo)函數(shù)
F=-(x1.^2+2*x2.^2-0.3*cos(3*pi*x1)-0.4*cos(4*pi*x2)+0.7);
End?
代碼片段和文件信息
function?[F]=F(x1x2)?%目標(biāo)函數(shù)
F=-(x1.^2+2*x2.^2-0.3*cos(3*pi*x1)-0.4*cos(4*pi*x2)+0.7);
End?
function?[maxxmaxymaxvalue]=antcolony%?蟻群算法求函數(shù)最大值的程序
ant=200;%螞蟻數(shù)量
times=50;%螞蟻移動(dòng)次數(shù)
rou=0.8;%信息素?fù)]發(fā)系數(shù)
p0=0.2;%轉(zhuǎn)移概率常數(shù)
lower_1=-1;%設(shè)置搜索范圍
upper_1=1;%
lower_2=-1;%
upper_2=1;%
for?i=1:ant??
????X(i1)=(lower_1+(upper_1-lower_1)*rand);%隨機(jī)設(shè)置螞蟻的初值位置
????X(i2)=(lower_2+(upper_2-lower_2)*rand);
????tau(i)=F(X(i1)X(i2));%第i只螞蟻的信息量?end?%隨機(jī)初始每只螞蟻的位置
????step=0.05;%網(wǎng)格劃分單位
????f=‘-(x.^2+2*y.^2-0.3*cos(3*pi*x)-0.4*cos(4*pi*y)+0.7)‘;
????[xy]=meshgrid(lower_1:step:upper_1lower_2:step:upper_2);
????z=eval(f);%eval函數(shù),將字符串內(nèi)的內(nèi)容執(zhí)行再賦給對(duì)象
????figure(1);
????mesh(xyz);%網(wǎng)格圖?
????hold?on;
????plot3(X(:1)X(:2)tau‘k*‘)%螞蟻初始位置
????hold?on;
????text(0.10.8-0.1‘螞蟻的初始分部位置‘)
????xlabel(‘x‘);
????ylabel(‘y‘);
????zlabel(‘f(xy)‘);
????for?t=1:times?%第t次移動(dòng)
????????lamda=1/t;?%步長(zhǎng)系數(shù),隨移動(dòng)次數(shù)增大而減少?
????[tau_best(t)bestindex]=max(tau);%第t次移動(dòng)的最優(yōu)值及其位置
?????????for?i=1:ant?%第i只螞蟻?
????????????p(ti)=(tau(bestindex)-tau(i))/tau(bestindex);%最優(yōu)值與第i只螞蟻的值的差比
??????????????%計(jì)算狀態(tài)轉(zhuǎn)移概率
????????end??
????????for?i=1:ant
????????????if?p(ti) ????????????????temp1=X(i1)+(2*rand-1)*lamda;%移動(dòng)
評(píng)論
共有 條評(píng)論