粒子群算法matlab实例
时间: 2023-09-04 07:06:36 浏览: 100
MatlabSamples-粒子群算法matlab实例
以下是一个简单的粒子群算法Matlab实例:
```
function [x, y] = PSO(f, lb, ub, dim, pop_size, max_iter)
% f:目标函数
% lb:自变量下限
% ub:自变量上限
% dim:自变量个数
% pop_size:粒子数
% max_iter:最大迭代次数
w = 0.729; % 惯性权重
c1 = 1.49445; % 学习因子1
c2 = 1.49445; % 学习因子2
% 初始化粒子位置和速度
pop = rand(pop_size, dim) .* (ub - lb) + lb;
vel = rand(pop_size, dim) .* (ub - lb) - (ub - lb) / 2;
% 计算初始适应度值和最优解
for i = 1:pop_size
fit(i) = f(pop(i, :));
end
[~, idx] = min(fit);
pbest = pop;
gbest = pop(idx, :);
% 迭代更新
for iter = 1:max_iter
for i = 1:pop_size
% 更新速度和位置
vel(i, :) = w * vel(i, :) + c1 * rand(1, dim) .* (pbest(i, :) - pop(i, :)) + c2 * rand(1, dim) .* (gbest - pop(i, :));
pop(i, :) = pop(i, :) + vel(i, :);
% 边界处理
pop(i, :) = max(pop(i, :), lb);
pop(i, :) = min(pop(i, :), ub);
% 更新个体最优解
fit(i) = f(pop(i, :));
if fit(i) < f(pbest(i, :))
pbest(i, :) = pop(i, :);
end
end
% 更新全局最优解
[~, idx] = min(fit);
if fit(idx) < f(gbest)
gbest = pop(idx, :);
end
% 输出迭代结果
fprintf('Iter = %d, Best = %f\n', iter, f(gbest));
end
% 返回最优解和适应度值
x = gbest;
y = f(gbest);
end
```
使用示例:
```
f = @(x) sum(x.^2); % 目标函数:多维球面函数
lb = -5; % 自变量下限
ub = 5; % 自变量上限
dim = 10; % 自变量个数
pop_size = 50; % 粒子数
max_iter = 100; % 最大迭代次数
[x, y] = PSO(f, lb, ub, dim, pop_size, max_iter); % 调用PSO函数
fprintf('Best x = ');
fprintf('%.4f ', x);
fprintf('\nBest y = %.4f\n', y);
```
输出结果:
```
Iter = 1, Best = 0.724462
Iter = 2, Best = 0.614443
Iter = 3, Best = 0.614443
Iter = 4, Best = 0.614443
...
Iter = 98, Best = 0.000000
Iter = 99, Best = 0.000000
Iter = 100, Best = 0.000000
Best x = 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Best y = 0.0000
```
阅读全文