clear;
clc;
close all;
a=[95,4,60,32,23,72,80,62,65,46]; %物品体积
c=[55,10,47,5,4,50,8,61,85,87]; %物品价值
b=269; %背包重量
%初始化种群
Dim=10; %维度
xSize=20; %种群数
maxgen=30; %迭代次数
c1=0.7;
c2=0.7; %加速因子
w=0.8; %定义惯性因子
%
A=repmat(a,xSize,1); %将a扩展成30*10的矩阵
C=repmat(c,xSize,1); %c扩展为30*10的矩阵
x=round(rand(xSize,Dim)); %随机一个30*10的矩阵
v=rand(xSize,Dim) %随机一个30*10的速度矩阵
xbest=zeros(xSize,Dim); %单个粒子的初始最佳位置
fxbest=zeros(xSize,1); %xbext的适应度
gbest=zeros(1,Dim); %全局最优解
fgbest=0; %全局最优解的适应度
%
%寻找粒子群最优位置和单个粒子
iter=0;
while iter<maxgen
iter=iter+1;
fx=sum((C.*x)'); %粒子适应度,即背包内物品的价格
sx=sum((A.*x)'); %限制函数,背包内物品的体积
for i=1:xSize
if sx(i)>269
fx(i)=0; %超过体积,适应度为0
end
end
for i=1:xSize
if fxbest(i)<fx(i) %当粒子适应度大于最佳适应度时,替代
fxbest(i)=fx(i);
xbest(i,:)=x(i,:);
end
end
if fgbest<max(fxbest)
[fgbest,g]=max(fxbest);
gbest=xbest(g,:) %当存在粒子的最佳适应度fxbext(i)大于种群最佳适应度fgbext(i)时,替代
end
for i=1:xSize
if x(i,:)==gbest
x(i,:)=round(rand(1,Dim)); %当某个粒子的位置为最佳位置时,重新赋值,以防止陷入局部最优解
end
end
R1=rand(xSize,Dim);
R2=rand(xSize,Dim);
v=v*w+c1*R1.*(xbest-x)+c2*R2.*(repmat(gbest,xSize,1)-x);%速度迭代公式产生新的速度
x=x+v;
for i=1:xSize %更新粒子群的位置
for j=1:Dim
if x(i,j)<0.5
x(i,j)=0;
else x(i,j)=1; %粒子的位置只有(0,1)两种状态
end
end
end
end
fgbest
sgbest=sum((a.*gbest)')
disp(gbest);