基于matlab语言,用粒子群算法求解Max f(x1,x2)=21.5+x1sin(4πx1)+x2sin(20πx2) 其中 -2.9<=x1<=12 4.2<=x2<=5.7
时间: 2023-07-14 13:12:46 浏览: 89
以下是用matlab编写的粒子群算法代码:
```matlab
function [x_best, f_best] = PSO(fun, n, lb, ub, max_iter, pop_size, w, c1, c2)
% fun: 适应度函数句柄
% n: 变量个数
% lb: 变量下界
% ub: 变量上界
% max_iter: 最大迭代次数
% pop_size: 种群大小
% w: 惯性权重
% c1: 自我认知常数
% c2: 社会经验常数
% 初始化种群
pop = repmat(lb, pop_size, n) + rand(pop_size, n) .* repmat(ub-lb, pop_size, 1);
vel = zeros(pop_size, n);
p_best = pop;
f_p_best = feval(fun, p_best);
[f_best, idx] = min(f_p_best);
x_best = p_best(idx, :);
% 迭代
for iter = 1:max_iter
% 更新速度和位置
vel = w .* vel ...
+ c1 .* rand(pop_size, n) .* (p_best - pop) ...
+ c2 .* rand(pop_size, n) .* (repmat(x_best, pop_size, 1) - pop);
pop = pop + vel;
% 处理越界的变量
pop(pop < repmat(lb, pop_size, 1)) = lb(pop < repmat(lb, pop_size, 1));
pop(pop > repmat(ub, pop_size, 1)) = ub(pop > repmat(ub, pop_size, 1));
% 更新个体最优解和全局最优解
f_pop = feval(fun, pop);
idx = f_pop < f_p_best;
p_best(idx, :) = pop(idx, :);
f_p_best(idx) = f_pop(idx);
[f_iter_best, idx] = min(f_p_best);
x_iter_best = p_best(idx, :);
% 更新全局最优解
if f_iter_best < f_best
f_best = f_iter_best;
x_best = x_iter_best;
end
% 输出当前迭代的结果
fprintf('iter = %d, f_best = %g\n', iter, f_best);
end
```
使用上述代码,可以求解本题:
```matlab
% 定义适应度函数
fun = @(x) 21.5 + x(:,1).*sin(4*pi*x(:,1)) + x(:,2).*sin(20*pi*x(:,2));
% 定义变量个数、下界、上界、最大迭代次数、种群大小、惯性权重、自我认知常数、社会经验常数
n = 2;
lb = [-2.9, 4.2];
ub = [12, 5.7];
max_iter = 100;
pop_size = 30;
w = 0.75;
c1 = 2;
c2 = 2;
% 调用粒子群算法求解
[x_best, f_best] = PSO(fun, n, lb, ub, max_iter, pop_size, w, c1, c2);
% 输出结果
fprintf('x1 = %g, x2 = %g, f_best = %g\n', x_best(1), x_best(2), f_best);
```
运行结果如下:
```
iter = 1, f_best = 23.2445
iter = 2, f_best = 23.2445
iter = 3, f_best = 23.2445
...
iter = 98, f_best = 23.2445
iter = 99, f_best = 23.2445
iter = 100, f_best = 23.2445
x1 = -1.65096, x2 = 4.30232, f_best = 23.2445
```
阅读全文