PSO算法matlab代码
时间: 2023-08-02 18:12:16 浏览: 45
下面是一个简单的PSO算法的Matlab代码,实现了对Rosenbrock函数的优化:
```matlab
% PSO算法实现对Rosenbrock函数的优化
clear; clc; close all;
% 设置参数
nPop = 50; % 种群大小
maxIter = 1000; % 最大迭代次数
wMax = 0.9; % 惯性权重上限
wMin = 0.4; % 惯性权重下限
c1 = 2; % 学习因子1
c2 = 2; % 学习因子2
Vmax = 4; % 粒子速度上限
% 初始化种群
dim = 2; % 变量维数
xMax = 2; % 变量上限
xMin = -2; % 变量下限
x = repmat(xMin, nPop, dim) + rand(nPop, dim) .* repmat((xMax - xMin), nPop, 1);
v = zeros(nPop, dim);
pBest = x;
fPbest = zeros(nPop, 1);
for i = 1:nPop
fPbest(i) = rosenbrock(pBest(i,:));
end
[~, gBestIndex] = min(fPbest);
gBest = pBest(gBestIndex,:);
% 迭代优化
for iter = 1:maxIter
% 更新速度和位置
w = wMax - (wMax - wMin) * iter / maxIter; % 更新惯性权重
for i = 1:nPop
v(i,:) = w * v(i,:) + c1 * rand(1,dim) .* (pBest(i,:) - x(i,:)) + c2 * rand(1,dim) .* (gBest - x(i,:)); % 更新速度
v(i,:) = max(min(v(i,:), Vmax), -Vmax); % 限制速度范围
x(i,:) = x(i,:) + v(i,:); % 更新位置
x(i,:) = max(min(x(i,:), xMax), xMin); % 限制位置范围
end
% 更新个体最优解和全局最优解
for i = 1:nPop
f = rosenbrock(x(i,:));
if f < fPbest(i)
pBest(i,:) = x(i,:);
fPbest(i) = f;
end
end
[~, gBestIndex] = min(fPbest);
gBest = pBest(gBestIndex,:);
% 显示迭代过程
disp(['Iteration ' num2str(iter) ': Best Cost = ' num2str(fPbest(gBestIndex))]);
end
% 画出优化结果
x1 = linspace(xMin, xMax, 100);
x2 = linspace(xMin, xMax, 100);
[X1,X2] = meshgrid(x1,x2);
F = rosenbrock([X1(:) X2(:)]);
F = reshape(F,length(x2),length(x1));
contour(X1,X2,F,50); hold on;
scatter(pBest(:,1), pBest(:,2), 'r.');
scatter(gBest(1), gBest(2), 'ko', 'LineWidth', 2);
title(['Minimum of Rosenbrock Function = ' num2str(rosenbrock(gBest))]);
xlabel('x_1'); ylabel('x_2');
```
其中,rosenbrock函数为:
```matlab
function f = rosenbrock(x)
% 计算Rosenbrock函数的值
% x: 变量向量
% f: Rosenbrock函数的值
f = sum(100 * (x(:,2:end) - x(:,1:end-1).^2).^2 + (1 - x(:,1:end-1)).^2, 2);
end
```
这里只是一个简单的PSO算法实现,实际应用中需要根据具体问题进行参数调整和改进。