粒子群算法

%% I. 清空环境
clc
clear
close all
%% II. 绘制曲线
figure
[x,y] = meshgrid(-5:0.1:5,-5:0.1:5);
z = x.^2 + y.^2 - 10*cos(2*pi*x) - 10*cos(2*pi*y) + 20;
mesh(x,y,z)
hold on
%% III. 参数的初始化
popsize = 100;%种群规模
c1 = 1.49445;
c2 = 1.49445;
kmax = 300;%最大迭代次数

popmax = 5;
popmin = -5;

Vmax = 1;
Vmin = -1;

% 初始化种群的速度和位置
for i = 1:popsize
    pop(i,:) = 5*rands(1,2);     %初始化粒子的位置
    V(i,:) = rands(1,2);            %初始化粒子的速度
    fitness(i) = func1(pop(i,:));%计算粒子的适应度值
end
 
%% IV. Pbest_i Gbest
[best_fintness,best_index] = max(fitness);
Gbest = pop(best_index,:);%群体最优的位置
Pbest = pop;                      %粒子的个体最优位置
fitnessPbest = fitness;           %粒子个体最优适应度值
fitnessGbest = best_fintness;%粒子群体最优适应度值

%% V. 迭代寻优
for k = 1:kmax
    % 更新粒子的位置和位置
    for j = 1:popsize
        %更新粒子的速度
        V(j,:) = V(j,:) + c1*rand*(Pbest(j,:) - pop(j,:)) + c2*rand*(Gbest - pop(j,:));
        %速度的越界处理
        V(j,find(V(j,:)>Vmax)) = Vmax;
        V(j,find(V(j,:)<Vmin)) = Vmin;
        
        %更新粒子的位置
        pop(j,:) = pop(j,:) + V(j,:);
        %位置的越界处理
        pop(j,find(pop(j,:)>popmax)) = popmax;
        pop(j,find(pop(j,:)<popmin)) = popmin;
        
        %更新适应度值
        fitness(j) = func1(pop(j,:));
    end
    
    for j = 1:popsize
        %更新给体最优
        if fitness(j) > fitnessPbest(j)
            Pbest(j,:) = pop(j,:);
            fitnessPbest(j) = fitness(j);
        end
        
        %更新群体最优
        if fitness(j) > fitnessGbest
            Gbest = pop(j,:);
            fitnessGbest = fitness(j);
        end
    end
        Best(k) = fitnessGbest;%用于存储每次迭代产生的最优适应度值
end
    
%% VI. 输出结果
[fitnessGbest,Gbest]
plot3(Gbest(1),Gbest(2),fitnessGbest,'bo')

figure
plot(Best)

 通过粒子群算法实现函数最大值求解,并画出适应度图,适用于新手学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ACanary

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值