粒子群算法matlab实例
时间: 2023-09-05 16:13:39 浏览: 32
下面是粒子群算法的matlab实例:
```matlab
%% 粒子群算法实现
clc, clear
% 目标函数
fun = @(x) x(1)^2 + x(2)^2 + x(3)^2;
% 粒子数
n = 20;
% 迭代次数
maxIter = 100;
% 惯性权重
w = 0.8;
% 加速常数
c1 = 1.5;
c2 = 1.5;
% 粒子的位置和速度范围
posMin = -5;
posMax = 5;
velMin = -1;
velMax = 1;
% 初始化粒子位置
pos = posMin + (posMax - posMin) * rand(3, n);
% 初始化粒子速度
vel = velMin + (velMax - velMin) * rand(3, n);
% 初始化个体最佳位置和适应度
pbestPos = pos;
pbestFit = zeros(1, n);
for i = 1 : n
pbestFit(i) = fun(pbestPos(:, i));
end
% 初始化全局最佳位置和适应度
[gbestFit, gbestIndex] = min(pbestFit);
gbestPos = pbestPos(:, gbestIndex);
% 记录每次迭代的最佳适应度
fitHistory = zeros(1, maxIter);
% 迭代
for iter = 1 : maxIter
% 更新粒子速度和位置
vel = w * vel + c1 * rand(3, n) .* (pbestPos - pos) + c2 * rand(3, n) .* (gbestPos - pos);
pos = pos + vel;
% 边界处理
pos(pos < posMin) = posMin;
pos(pos > posMax) = posMax;
% 更新个体最佳位置和适应度
for i = 1 : n
fit = fun(pos(:, i));
if fit < pbestFit(i)
pbestFit(i) = fit;
pbestPos(:, i) = pos(:, i);
end
end
% 更新全局最佳位置和适应度
[minFit, minIndex] = min(pbestFit);
if minFit < gbestFit
gbestFit = minFit;
gbestPos = pbestPos(:, minIndex);
end
% 记录每次迭代的最佳适应度
fitHistory(iter) = gbestFit;
end
% 输出结果
gbestFit
gbestPos
% 绘制适应度变化曲线
plot(fitHistory)
xlabel('迭代次数')
ylabel('最佳适应度')
title('粒子群算法')
```
该实例中,目标函数为 $f(x)=x_1^2+x_2^2+x_3^2$,粒子数为 20,迭代次数为 100。粒子的位置和速度范围均为 $[-5,5]$,惯性权重为 0.8,加速常数为 1.5。在迭代过程中,通过更新粒子速度和位置,记录每次迭代的最佳适应度,最终输出全局最佳位置和适应度,以及绘制适应度变化曲线。