
popsize=20
MAXITER=2000
dimension=30
irange_l=-5.12
irange_r=5.12
xmax=10
sum1=0
sum2=0
mean=0
st=0
runno=10
data1=zeros(runno,MAXITER)
for run=1:runno
T=cputime
x=(irange_r- irange_l)*rand(popsize,dimension,1) + irange_l
pbest=x
gbest=zeros(1,dimension)
for i=1:popsize
f_x(i)=f3(x(i,:))
f_pbest(i)=f_x(i)
end
g=min(find(f_pbest==min(f_pbest(1:popsize))))
gbest=pbest(g,:)
f_gbest=f_pbest(g)
MINIUM=f_pbest(g)
for t=1:MAXITER
beta=(1-0.5)*(MAXITER-t)/MAXITER+0.5
mbest=sum(pbest)/popsize
for i=1:popsize
fi=rand(1,dimension)
p=fi.*pbest(i,:)+(1-fi).*gbest
u=rand(1,dimension)
b=beta*(mbest-x(i,:))
v=-log(u)
y=p+((-1).^ceil(0.5+rand(1,dimension))).*b.*v
x(i,:)=y
x(i,:)=sign(y).*min(abs(y),xmax)
f_x(i)=f3(x(i,:))
if f_x(i)<f_pbest(i)
pbest(i,:)=x(i,:)
f_pbest(i)=f_x(i)
end
if f_pbest(i)<f_gbest
gbest=pbest(i,:)
f_gbest=f_pbest(i)
end
MINIUM=f_gbest
end
data1(run,t)=MINIUM
if MINIUM>1e-007
mean=t
end
end
sum1=sum1+mean
sum2=sum2+MINIUM
%MINIUM
time=cputime-T
st=st+time
end
av1=sum1/10 %输出平均收验代数
av2=sum2/10 %输出平均最优解
st/10 %就是最后anw输出的解
%不知道你具体的问题是什么,下面是一个最基本的pso算法解决函数极值问题,如果是一些大型的问题,需要对速度、惯性常数、和自适应变异做进一步优化,希望对你有帮助function y = fun(x)
y=-20*exp(-0.2*sqrt((x(1)^2+x(2)^2)/2))-exp((cos(2*pi*x(1))+cos(2*pi*x(2)))/2)+20+2.71289
%下面是主程序
%% 清空环境
clc
clear
%% 参数初始化
%粒子群算法中的两个参数
c1 = 1.49445
c2 = 1.49445
maxgen=200 % 进化次数
sizepop=20 %种群规模
Vmax=1%速度限制
Vmin=-1
popmax=5%种群限制
popmin=-5
%% 产生初始粒子和速度
for i=1:sizepop
%随机产生一个种群
pop(i,:)=5*rands(1,2) %初始种群
V(i,:)=rands(1,2) %初始化速度
%计算适应度
fitness(i)=fun(pop(i,:)) %染色体的适应度
end
%找最好的染色体
[bestfitness bestindex]=min(fitness)
zbest=pop(bestindex,:) %全局最佳
gbest=pop %个体最佳
fitnessgbest=fitness %个体最佳适应度值
fitnesszbest=bestfitness %全局最佳适应度值
%% 迭代寻优
for i=1:maxgen
for j=1:sizepop
%速度更新
V(j,:) = V(j,:) + c1*rand*(gbest(j,:) - pop(j,:)) + c2*rand*(zbest - pop(j,:))
V(j,find(V(j,:)>Vmax))=Vmax
V(j,find(V(j,:)<Vmin))=Vmin
%种群更新
pop(j,:)=pop(j,:)+0.5*V(j,:)
pop(j,find(pop(j,:)>popmax))=popmax
pop(j,find(pop(j,:)<popmin))=popmin
%自适应变异(避免粒子群算法陷入局部最优)
if rand>0.8
k=ceil(2*rand)%ceil朝正无穷大方向取整
pop(j,k)=rand
end
%适应度值
fitness(j)=fun(pop(j,:))
%个体最优更新
if fitness(j) <fitnessgbest(j)
gbest(j,:) = pop(j,:)
fitnessgbest(j) = fitness(j)
end
%群体最优更新
if fitness(j) <fitnesszbest
zbest = pop(j,:)
fitnesszbest = fitness(j)
end
end
yy(i)=fitnesszbest
end
%% 结果分析
plot(yy)
title(['适应度曲线 ' '终止代数=' num2str(maxgen)])
xlabel('进化代数')ylabel('适应度')
以上回答你满意么?
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)