最后在煉數成金那邊找到了很好的一篇教程
在這里把它整理一下
做個粒子群算法的收尾



main.m
%% I. 清空環境
clc
clear
%% 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. 參數初始化
c1 = 1.49445;
c2 = 1.49445;
maxgen = 1000; % 進化次數
sizepop = 100; %種群規模
Vmax = 1;
Vmin = -1;
popmax = 5;
popmin = -5;
%% IV. 產生初始粒子和速度
for i = 1:sizepop
% 隨機產生一個種群
pop(i,:) = 5*rands(1,2); %初始種群
V(i,:) = rands(1,2); %初始化速度
% 計算適應度
fitness(i) = fun(pop(i,:)); %染色體的適應度
end
%% V. 個體極值和群體極值
[bestfitness bestindex] = max(fitness);
zbest = pop(bestindex,:); %全局最佳
gbest = pop; %個體最佳
fitnessgbest = fitness; %個體最佳適應度值
fitnesszbest = bestfitness; %全局最佳適應度值
%% VI. 迭代尋優
for i = 1:maxgen
for j = 1:sizepop
% 速度更新
V(j,:) = V(j,:) + c1*rand*(gbest(j,:) - pop(j,:)) + c2*rand*(zbest - 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) = fun(pop(j,:));
end
for j = 1:sizepop
% 個體最優更新
if fitness(j) > fitnessgbest(j)
gbest(j,:) = pop(j,:);
fitnessgbest(j) = fitness(j);
end
% 群體最優更新
if fitness(j) > fitnesszbest
zbest = pop(j,:);
fitnesszbest = fitness(j);
end
end
yy(i) = fitnesszbest;
end
%% VII.輸出結果
[fitnesszbest, zbest]
plot3(zbest(1), zbest(2), fitnesszbest,'bo','linewidth',1.5)
figure
plot(yy)
title('最優個體適應度','fontsize',12);
xlabel('進化代數','fontsize',12);ylabel('適應度','fontsize',12);
fun.m
function y = fun(x) %函數用於計算粒子適應度值 %x input 輸入粒子 %y output 粒子適應度值 y = x(1).^2 + x(2).^2 - 10*cos(2*pi*x(1)) - 10*cos(2*pi*x(2)) + 20;


