用MATLAB写粒子群优化算法的程序
时间: 2023-06-30 08:09:15 浏览: 38
下面是一个简单的粒子群优化算法的 MATLAB 程序示例:
```matlab
function [x_opt, f_opt] = pso(fitness_func, n_dim, n_particles, n_iter)
% fitness_func: 适应度函数
% n_dim: 搜索空间的维度
% n_particles: 粒子群中的粒子数
% n_iter: 迭代次数
% 初始化
x_min = -10; x_max = 10; % 搜索空间的范围
w = 0.7; c1 = 1.4; c2 = 1.4; % 粒子群算法的参数
x = x_min + (x_max - x_min) * rand(n_particles, n_dim); % 粒子位置
v = zeros(n_particles, n_dim); % 粒子速度
p_best = x; % 粒子历史最佳位置
p_best_fit = feval(fitness_func, p_best); % 粒子历史最佳适应度
g_best = x(1,:); % 全局最佳位置
g_best_fit = feval(fitness_func, g_best); % 全局最佳适应度
% 迭代
for i = 1:n_iter
v = w * v + c1 * rand(n_particles, n_dim) .* (p_best - x) + c2 * rand(n_particles, n_dim) .* (g_best - x);
x = x + v;
x(x < x_min) = x_min; x(x > x_max) = x_max; % 限制粒子位置在搜索空间范围内
fit = feval(fitness_func, x);
update = fit > p_best_fit;
p_best(update,:) = x(update,:); p_best_fit(update) = fit(update);
[fit_min, ind] = min(p_best_fit);
if fit_min < g_best_fit
g_best = p_best(ind,:); g_best_fit = fit_min;
end
end
x_opt = g_best;
f_opt = g_best_fit;
end
```
你需要自己定义适应度函数 `fitness_func`,其输入是粒子的位置,输出是对应的适应度值。在 `pso` 函数中, `n_dim` 是搜索空间的维度, `n_particles` 是粒子群中的粒子数, `n_iter` 是迭代次数。函数最终返回全局最佳位置 `x_opt` 和全局最佳适应度值 `f_opt`。
使用示例:
```matlab
% 定义适应度函数
fitness_func = @(x) sum(x.^2, 2);
% 运行粒子群优化算法
n_dim = 2; n_particles = 50; n_iter = 100;
[x_opt, f_opt] = pso(fitness_func, n_dim, n_particles, n_iter);
% 输出结果
fprintf('全局最优解: x1 = %.2f, x2 = %.2f\n', x_opt);
fprintf('全局最优适应度: %.2f\n', f_opt);
```