📄 mypso.m
字号:
% 连续函数的粒子群算法
% Author: xixilee
% Date: 2007-5-26
function best = MyPSO()
clc;
clear;
close all;
c1 = 2; % 学习因子
c2 = 2; % 学习因子
wIni = 0.9; % 初始惯性因子
wEnd = 0.4; % 迭代至最大惯性代数时的惯性因子
popSize = 100; % 群体规模
dimension = 30; % 空间维数
iterMax = 1500; % 最大进化代数
% 粒子群初始化
xMin = 0; % 粒子位置的最小值
xMax = 5; % 粒子位置的最大值
vMax = (xMax - xMin)/4; % 最大限制速度
vMin = -vMax; % 最小限制速度
x = zeros(popSize, dimension + 1); % 粒子位置
v = zeros(popSize, dimension); % 粒子速度
for i = 1: popSize
for j = 1: dimension
x(i, j) = xMin + (xMax - xMin)*rand; % 粒子位置初始化
v(i, j) = vMax*rand; % 粒子速度初始化
end
x(i, end) = fitness(x(i, 1: dimension)); % 适应度评估
end
pBest = zeros(popSize, dimension + 1); % 个体最优位置
pBest = x; % 个体最优位置初始化
gBest = zeros(1, dimension + 1); % 群体最优位置
[temp index] = min(pBest(:, end));
gBest = pBest(index, :); % 群体最优位置初始化
% 进化
for iter = 1:iterMax
w = (wIni - wEnd)*(iterMax - iter)/iterMax + wEnd; % 惯性因子
for i = 1: popSize
% 粒子速度更新
tempV = [];
tempV = w.*v(i, :) + c1.*rand.*(pBest(i, 1: dimension) - x(i, 1: dimension)) ...
+ c2.*rand.*(gBest(1: dimension) - x(i, 1: dimension)); % 粒子速度更新
for j = 1: dimension
if tempV(j) > vMax
v(i, j) = vMax;
elseif tempV(j) < vMin
v(i, j) = vMin;
else
v(i, j) = tempV(j);
end
end
% 粒子位置更新
tempX = [];
tempX = x(i, 1: dimension) + v(i , :); % 粒子位置更新
for j = 1: dimension
if tempX(j) > xMax
x(i, j) = xMax;
elseif tempX(j) < xMin
x(i, j) = xMin;
else
x(i, j) = tempX(j);
end
end
end
% 个体最优位置更新
for i = 1: popSize
x(i, end) = fitness(x(i, 1: dimension)); % 适应度评估
if x(i, end) < pBest(i, end);
pBest(i, :) = x(i, :);
end
end
% 群体最优位置更新
if min(pBest(:, end)) < gBest(end)
[temp index] = min(pBest(:, end));
gBest = pBest(index, :);
end
best(iter) = gBest(end); % 保存每一代的最优适应度
end
save solution_mypso.txt best -ASCII
semilogy(best)
% 适应度评估函数
function f = fitness(x)
% dim=length(x);
% tmp=[];
% for i=1:dim
% tmp(i)=x(i)-i;
% end
% f = sum(tmp.^2);
f = sum(x.^2, 2);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -