%% Shubert函数 % 输入:x和y向量 % 输出:函数值f function f = Shubert(x, y) A = 0; B = 0; for i = 1:5 A = A + i * cos((i + 1) * x + i); B = B + i * cos((i + 1) * y + i); end f = A * B; end

%% PSO算法 % 输入:目标函数f、粒子个数num、最大迭代次数max_iter、惯性权重w、加速系数c1和c2 % 输出:全局最优解best_x、全局最优解对应的函数值best_f function [best_x, best_f] = PSO(f, num, max_iter, w, c1, c2) % 初始化粒子群 position = 10 * rand(num, 2) - 5; velocity = zeros(num, 2); pbest_position = position; pbest_f = arrayfun(f, position(:,1), position(:,2)); [best_f, index] = min(pbest_f); best_x = pbest_position(index,:);

% 开始迭代
for iter = 1:max_iter
    % 更新速度和位置
    r1 = rand(num, 1);
    r2 = rand(num, 1);
    velocity = w * velocity + c1 * r1 .* (pbest_position - position) + c2 * r2 .* (repmat(best_x,num,1) - position);
    position = position + velocity;
    
    % 计算适应度值
    f_val = arrayfun(f, position(:,1), position(:,2));
    
    % 更新个体最优解
    update = f_val < pbest_f;
    pbest_position(update,:) = position(update,:);
    pbest_f(update) = f_val(update);
    
    % 更新全局最优解
    [min_f, index] = min(pbest_f);
    if min_f < best_f
        best_f = min_f;
        best_x = pbest_position(index,:);
    end
end

end

%% 主函数 % 在Shubert函数上运行PSO算法,找出全局最小值和对应的解 num = 100; max_iter = 100; w = 0.8; c1 = 1.5; c2 = 1.5; [best_x, best_f] = PSO(@Shubert, num, max_iter, w, c1, c2); fprintf('全局最小值为%f,对应的解为(%f,%f)\n', best_f, best_x(1), best_x(2));

% 找出所有全局最小值的解 solutions = []; for i = -5:0.01:5 for j = -5:0.01:5 if abs(Shubert(i,j) - best_f) < 1e-6 solutions = [solutions; [i,j]]; end end end fprintf('共有%d个全局最小值,分别为:\n', size(solutions,1)); disp(solutions)


原文地址: https://www.cveoy.top/t/topic/cfIJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录