基于matlab语言,用粒子群算法求解Max f(x1,x2)=21.5+x1sin(4πx1)+x2sin(20πx2) 其中 -2.9<=x1<=12 4.2<=x2<=5.7
时间: 2023-06-26 08:07:14 浏览: 180
粒子群算法求解函数极值 matlab
下面是用粒子群算法求解最大值的MATLAB代码:
```matlab
clear;clc;
% 参数设置
w = 0.5; % 惯性权重
c1 = 2; c2 = 2; % 加速因子
max_iter = 100; % 迭代次数
pop_size = 20; % 粒子数
dim = 2; % 变量维度
x_min = [-2.9, 4.2]; % 变量下限
x_max = [12, 5.7]; % 变量上限
% 初始化种群
pop = rand(pop_size, dim) .* (x_max - x_min) + x_min;
v = zeros(pop_size, dim);
pbest = pop;
gbest = pbest(1, :);
% 计算适应度
fit = @(x) -(21.5 + x(1)*sin(4*pi*x(1)) + x(2)*sin(20*pi*x(2)));
pbest_fit = arrayfun(fit, pbest);
[~, gbest_index] = max(pbest_fit);
gbest = pbest(gbest_index, :);
% 迭代寻优
for i = 1:max_iter
% 更新速度和位置
v = w*v + c1*rand(pop_size,dim).*(pbest-pop) + c2*rand(pop_size,dim).*(repmat(gbest,pop_size,1)-pop);
pop = pop + v;
% 越界处理
pop(pop<x_min) = x_min(pop<x_min);
pop(pop>x_max) = x_max(pop>x_max);
% 计算适应度
pbest_fit_new = arrayfun(fit, pop);
% 更新个体最优解
update_index = pbest_fit_new < pbest_fit;
pbest(update_index,:) = pop(update_index,:);
pbest_fit(update_index) = pbest_fit_new(update_index);
% 更新全局最优解
[min_pbest_fit, index] = min(pbest_fit);
if min_pbest_fit < fit(gbest)
gbest = pbest(index, :);
end
% 输出结果
disp(['Iteration: ', num2str(i), ', Best fitness value: ', num2str(-min_pbest_fit)]);
end
disp(['Optimal solution: x1=', num2str(gbest(1)), ', x2=', num2str(gbest(2)), ', Max f(x1,x2)=', num2str(-min_pbest_fit)]);
```
执行该代码后,将会输出每次迭代的最佳适应度值,以及最终的最优解和最大值。
阅读全文