%% PSO算法 % 输入:目标函数,粒子数,迭代次数,搜索范围 % 输出:所有最优解及其函数值 function [xopt_all, yopt_all, fopt_all] = PSO(objfun, np, maxiter, bounds) % 初始化粒子 x = rand(np, 1) * (bounds(2, 1) - bounds(1, 1)) + bounds(1, 1); y = rand(np, 1) * (bounds(2, 2) - bounds(1, 2)) + bounds(1, 2); v = zeros(np, 2); pbestx = x; pbesty = y; pbestf = inf(np, 1); for i = 1:np f = objfun(x(i), y(i)); if f < pbestf(i) pbestf(i) = f; end end gbesti = find(pbestf == min(pbestf)); gbestx = pbestx(gbesti); gbesty = pbesty(gbesti); gbestf = pbestf(gbesti); xopt_all = gbestx; yopt_all = gbesty; fopt_all = gbestf;

% 迭代优化
for iter = 1:maxiter
    w = 0.5; % 惯性权重
    c1 = 2; % 个体学习因子
    c2 = 2; % 社会学习因子
    for i = 1:np
        r1 = rand;
        r2 = rand;
        v(i, 1) = w * v(i, 1) + c1 * r1 * (pbestx(i) - x(i)) + c2 * r2 * (gbestx - x(i));
        x(i) = x(i) + v(i, 1);
        if x(i) < bounds(1, 1)
            x(i) = bounds(1, 1);
            v(i, 1) = -v(i, 1);
        elseif x(i) > bounds(2, 1)
            x(i) = bounds(2, 1);
            v(i, 1) = -v(i, 1);
        end

        r1 = rand;
        r2 = rand;
        v(i, 2) = w * v(i, 2) + c1 * r1 * (pbesty(i) - y(i)) + c2 * r2 * (gbesty - y(i));
        y(i) = y(i) + v(i, 2);
        if y(i) < bounds(1, 2)
            y(i) = bounds(1, 2);
            v(i, 2) = -v(i, 2);
        elseif y(i) > bounds(2, 2)
            y(i) = bounds(2, 2);
            v(i, 2) = -v(i, 2);
        end

        f = objfun(x(i), y(i));
        if f < pbestf(i)
            pbestf(i) = f;
            pbestx(i) = x(i);
            pbesty(i) = y(i);
            % 检查是否有新的最优解
            if f < fopt_all
                xopt_all = [xopt_all; x(i)];
                yopt_all = [yopt_all; y(i)];
                fopt_all = [fopt_all; f];
            end
        end
    end

    [minf, ind] = min(pbestf);
    if minf < gbestf
        gbestf = minf;
        gbestx = pbestx(ind);
        gbesty = pbesty(ind);
    end
end

end

%% 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

%% 寻找Shubert函数的全部最优解 % 输入:无 % 输出:所有最优解及其函数值

bounds = [-10, -10; 10, 10]; % 搜索范围 np = 100; % 粒子数 maxiter = 1000; % 迭代次数

% 定义Shubert函数 objfun = @(x,y) Shubert(x, y);

% 使用PSO算法求解 [xopt_all, yopt_all, fopt_all] = PSO(objfun, np, maxiter, bounds);

% 输出结果 disp('所有最优解及其函数值:'); for i = 1:length(fopt_all) fprintf('(%f, %f): %f\n', xopt_all(i), yopt_all(i), fopt_all(i)); end

PSO算法寻找Shubert函数的全部最优解

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

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