matlab粒子群算法代码实现
时间: 2023-09-01 22:07:48 浏览: 87
粒子群算法(Particle Swarm Optimization,PSO)是一种优化算法,它通过模拟鸟群捕食行为的方式来寻找最优解。下面是用MATLAB实现粒子群算法的代码示例:
```matlab
function [bestpos, bestfitness] = pso(fobj, dim, lb, ub, maxiter, npop, c1, c2, w)
% fobj: 目标函数
% dim: 变量维度
% lb: 变量下界
% ub: 变量上界
% maxiter: 最大迭代次数
% npop: 粒子数
% c1: 学习因子1
% c2: 学习因子2
% w: 惯性权重
% 初始化粒子群
pos = repmat(lb, npop, 1) + rand(npop, dim) .* repmat((ub-lb), npop, 1);
vel = zeros(npop, dim);
pbestpos = pos;
pbestfitness = ones(npop, 1) * inf;
% 寻找全局最优解
[gbestfitness, gbestid] = min(pbestfitness);
gbestpos = pbestpos(gbestid, :);
% 迭代
for iter = 1:maxiter
% 更新粒子速度和位置
vel = w * vel + c1 * rand(npop, dim) .* (pbestpos - pos) + c2 * rand(npop, dim) .* repmat((gbestpos - pos), npop, 1);
pos = pos + vel;
% 越界处理
pos(pos<lb) = lb(pos<lb);
pos(pos>ub) = ub(pos>ub);
% 更新每个粒子的最优解
fitness = feval(fobj, pos');
update = fitness < pbestfitness;
pbestpos(update, :) = pos(update, :);
pbestfitness(update) = fitness(update);
% 更新全局最优解
[tempgbestfitness, tempgbestid] = min(pbestfitness);
if tempgbestfitness < gbestfitness
gbestfitness = tempgbestfitness;
gbestpos = pbestpos(tempgbestid, :);
end
% 输出结果
fprintf('Iteration %d: Best fitness = %f\n', iter, gbestfitness);
end
bestpos = gbestpos;
bestfitness = gbestfitness;
end
```
使用方法:
定义一个目标函数,例如:
```matlab
function y = sphere(x)
y = sum(x.^2);
end
```
然后调用`pso`函数:
```matlab
fobj = @sphere;
dim = 10;
lb = -100;
ub = 100;
maxiter = 100;
npop = 50;
c1 = 2;
c2 = 2;
w = 0.7;
[bestpos, bestfitness] = pso(fobj, dim, lb, ub, maxiter, npop, c1, c2, w);
```
其中,`dim`是变量维度,`lb`和`ub`分别是变量的下界和上界,`maxiter`是最大迭代次数,`npop`是粒子数,`c1`和`c2`是学习因子,`w`是惯性权重。`bestpos`是最优解,`bestfitness`是最优解对应的目标函数值。
阅读全文